Suppose I have this database table (some sample code below) that stores the relationship between two lists (requirements and testcases in my case) and I want to create a table with rows showing testcases and columns showing requirements with an indicator showing that a relationship exists.
A few limitations
- I don’t have the luxury of changing the db structure as this belongs to an open source test case management system (TestLink).
- It’s possible to write some code for this, but I’m hoping it can be done in MySQL.
- Ah, and yes, it uses MySQL, so this would have to work in that environment.
-
This functionality used to exist, but has been taken out because typically, this type of work brings the db to its knees when there are tens-of-thousands of testcases and requirements.
create table
pivot(
req_idint(11),
testcase_idint(11)
) ;/*Data for the table
pivot*/insert into
pivot(req_id,testcase_id) values (1,1);insert into
pivot(req_id,testcase_id) values (2,2);insert into
pivot(req_id,testcase_id) values (3,3);insert into
pivot(req_id,testcase_id) values (4,1);insert into
pivot(req_id,testcase_id) values (5,2);insert into
pivot(req_id,testcase_id) values (6,3);insert into
pivot(req_id,testcase_id) values (2,1);insert into
pivot(req_id,testcase_id) values (3,2);
What I want to get out of the query is a table that looks somethign like this:
1 2 3 4 5 6
1 x x x
2 x x x
3 x x
Note:the row are the testcase_ids and the columns are the ‘req_ids’
Anyone have a tip on how to get this with just SQL?
I now have a name for what I’m trying to accomplish. It’s a ‘dynamic crosstab’. Here is how I got to the solution. Thanks to http://rpbouman.blogspot.com/2005/10/creating-crosstabs-in-mysql.html for the clear instructions for getting here.
Lines 1-20 – Set up a table to use for testing.
Lines 22-29 – a ‘static’ crosstab query, assuming I know how many requirements I’ve got.
Thanks D Mac for the solution you gave 🙂
Lines 30-44 – A query that dynamically generates the static query above.
Lines 45-72 – This is where I’m having the problem. The intent is to create a stored procedure that returns the result of the dynamic query. MySQL is saying there is a syntax issue, but I don’t see how to fix it. Any thoughts?