学习者。
曾尝试在网上寻找答案,但没有找到任何答案
这是一个创建的场景。实际的有点复杂。
一个包含3列,id,颜色和数量的表。样本数据是:
ID - 颜色 - 数量
1 - 红色 - 3
1 - 蓝 - 4
1 - 黄色 - 3
1 - 红色 - 4
1 - 蓝 - 2
运行以下查询:
SELECT id,
case when color='Red' then sum(quantity) else 0 end as red_quantity,
case when color='Yellow' then sum(quantity) else 0 end as yellow_quantity,
case when color='Blue' then sum(quantity) else 0 end as blue_quantity
from test group by id
预期结果是包含4列的单行,如下所示:
ID - red_quantity - yellow_quantity - blue_quantity
1--7--3--6。
取而代之的是:
1--16--0--0
据我所知,这是由于分组而发生的。但是替代方案是什么,最好是 - 不丢弃案件?
感谢帮助。
答案 0 :(得分:0)
您只需从案例中返回数量,并将案例包装在SUM中,而不是尝试在案例中求和。
SELECT id,
SUM(case when color='Red' then quantity else 0 end) as red_quantity,
SUM(case when color='Yellow' then quantity else 0 end) as yellow_quantity,
SUM(case when color='Blue' then quantity else 0 end) as blue_quantity
from test group by id
您的原始查询是说,如果相关行的颜色为红色,则将所有数量相加。 在整个案例中包含SUM意味着SUM只会从CASE中获取值 - 如果行是正确的颜色则为非零。
根据要求添加进一步说明。
您的查询无法正常工作的原因取决于MySQL如何在内部处理查询。 实际上,它在评估CASE陈述之前对记录进行分组,因为它没有"看到"你想要一个聚合。
因此,如果MySQL按照首先对您的记录进行分组,那么您将获得一条具有非确定性颜色的记录。
1 | red
如果您在此记录上运行CASE陈述,您将获得1-16-0-0
非确定性颜色可能很容易成为其他颜色,具体取决于MySQL如何在内部对记录进行排序。因此,您可以多次运行查询并获得不同的结果(1-0-16-0或1-0-0-16)。
答案 1 :(得分:0)
case
应该是sum()
的参数:
SELECT id,
sum(case when color = 'Red' then quantity else 0 end) as red_quantity,
sum(case when color = 'Yellow' then quantity else 0 end) as yellow_quantity,
sum(case when color = 'Blue' then quantit) else 0 end) as blue_quantity
from test
group by id