0

我有一个使用 SUM IF() 执行交叉表结果集的查询。在这个查询中,我有 SUM IF() 硬编码的值。问题是新值被添加到数据库中。有没有办法在不对 SUM IF() 中的值进行硬编码的情况下编写查询?这是查询:

选择 storeid, sum(if(marketsegmentid = 6, 1, 0)) as 6, sum(if(marketsegmentid = 7, 1, 0)) as 7, sum(if(marketsegmentid = 12, 1, 0)) as 12, sum( if(marketsegmentid = 17, 1, 0)) as 17, sum(if(marketsegmentid = 22, 1, 0)) as 22, sum(if(marketsegmentid = 27, 1, 0)) as 27, sum(if(marketsegmentid = 32 , 1, 0)) as 32, sum(if(marketsegmentid = 37, 1, 0)) as 37, sum(if(marketsegmentid = 42, 1, 0)) as 42, sum(if(marketsegmentid = 47, 1, 0) ) as 47, sum(if(marketsegmentid = 52, 1, 0)) as 52, sum(if(marketsegmentid = 97, 1, 0)) as 97, sum(if(marketsegmentid = 102, 1, 0)) as 102, sum( if(marketsegmentid = 107, 1, 0)) 作为107, sum(if(marketsegmentid = 112, 1, 0)) as 112, sum(if(marketsegmentid = 117, 1, 0)) as 117, sum(if(marketsegmentid = 122, 1, 0)) as 122, sum(if( marketsegmentid = 127, 1, 0)) as 127, sum(if(marketsegmentid = 132, 1, 0)) as 132, sum(if(marketsegmentid = 137, 1, 0)) as 137, sum(if(marketsegmentid = 142, 1 , 0))142 来自 storemarketsegments 按 storeid 分组;

查询在报告中使用,结果导出为 CSV。1 用作结果集中的标志。

我查询的表是这样设置的:

CREATE TABLE storemarketsegments(id INT NOT NULL, marketsegmentid INT NOT NULL);

市场细分保存在单独的表中:

创建表市场段(ID INT NOT NULL AUTO_INCREMENT,主键(id),名称 VARCHAR(45),描述 VARCHAR(45));

任何帮助将不胜感激。我不确定是否有一种方法可以在不对值进行硬编码的情况下编写查询,并且我不介意在添加新的市场细分时更新报告中的查询,但我想我会检查一下。预先感谢您的协助。

4

1 回答 1

2

您可以将每个计数作为单独的行返回,然后在应用层根据需要进行过滤:

select storeid, marketsegmentid, count(*) as Count
from storemarketsegments 
group by storeid, marketsegmentid;
于 2012-06-04T16:35:24.813 回答