我在mysql中有一个查询,它给了我这个
product count(*)
------- ---------
A 5
B 2
C 3
D 4
E 1
查询很简单,如
select product,count(*) from dashboard group by product;
现在问题是我想将某些产品的数量合并到其他产品中,例如预期的输出是
product count(*)
------- ---------
A 7
C 3
D 5
所以计数(A)=计数(A)+计数(B)
count(c)= count(C)
count(D)= count(D)+ count(E)
我在想这样的事情
select case
when product = 'A' OR product = 'B' then ----
when product = 'C' then ----
end
答案 0 :(得分:2)
第二次对现有结果进行分组(这具有显着优势,即如果可能的话,它将使用索引执行第一个聚合,然后使用较小的结果集执行第二个更简单的总和):
SELECT CASE
WHEN p IN ('A','B') THEN 'A'
WHEN p IN ('C') THEN 'C'
WHEN p IN ('D','E') THEN 'D'
END AS product, SUM(c)
FROM (
SELECT product AS p, COUNT(*) AS c
FROM dashboard
GROUP BY p
) t
GROUP BY product
在sqlfiddle上查看。
答案 1 :(得分:1)
您可以在子查询中将更改放置到产品中:
select product, count(*) Total
from
(
select
case
when product in ('A','B') then 'A'
when product in ('C') then 'C'
when product in ('D','E') then 'D'
end AS product
from dashboard
) src
group by product;