I have a query that uses SUM IF() to do a cross-tab result set. In this query I have the value sin the SUM IF() hard coded. The problem is that new values are added to the database. Is there a way to write the query without hard coding the values in the SUM IF()? Here is the query:
select storeid, sum(if(marketsegmentid = 6, 1, 0)) as
6,
sum(if(marketsegmentid = 7, 1, 0))
as7, sum(if(marketsegmentid = 12, 1, 0)) as12, sum(if(marketsegmentid = 17, 1, 0)) as17,
sum(if(marketsegmentid = 22, 1, 0)) as22, sum(if(marketsegmentid = 27, 1, 0)) as27,
sum(if(marketsegmentid = 32, 1, 0)) as32, sum(if(marketsegmentid = 37, 1, 0)) as37,
sum(if(marketsegmentid = 42, 1, 0)) as42, sum(if(marketsegmentid = 47, 1, 0)) as47,
sum(if(marketsegmentid = 52, 1, 0)) as52, sum(if(marketsegmentid = 97, 1, 0)) as97,
sum(if(marketsegmentid = 102, 1, 0)) as102, sum(if(marketsegmentid = 107, 1, 0)) as107,
sum(if(marketsegmentid = 112, 1, 0)) as112, sum(if(marketsegmentid = 117, 1, 0)) as117,
sum(if(marketsegmentid = 122, 1, 0)) as122, sum(if(marketsegmentid = 127, 1, 0)) as127,
sum(if(marketsegmentid = 132, 1, 0)) as132, sum(if(marketsegmentid = 137, 1, 0)) as137,
sum(if(marketsegmentid = 142, 1, 0)) as142
from storemarketsegments
group by storeid;
The query is used in a report and the results are exported to CSV. The 1’s are used as flags in the result set.
The table I am querying is set up like this:
CREATE TABLE storemarketsegments(id INT NOT NULL, marketsegmentid INT NOT NULL);
The marketsegments are kept in a separate table:
CREATE TABLE marketsegment(ID INT NOT NULL AUTO_INCREMENT, PRIMARY
KEY(id), name VARCHAR(45), description VARCHAR(45));
Any help would be greatly appreciated. I am not sure if there is a way to write the query without hard coding the values and I don’t mind updating the query in the report whenever new marketsegments are added but thought I would check. Thank you in advance for your assistance.
You can return each count as a separate row, and then filter as needed in the application layer: