1

我在 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)

计数(c) = 计数(C)

计数(D)= 计数(D) + 计数(E)

我在想这样的事情

select case
when product = 'A' OR product = 'B' then ----
when product = 'C' then ----
end
4

2 回答 2

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上查看。

于 2012-12-18T10:14:44.293 回答
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;

请参阅带有演示的 SQL Fiddle

于 2012-12-18T10:18:12.990 回答