在Mysql中对来自不同条件的行求和

时间:2014-04-25 21:26:54

标签: mysql

原始表很大,所以我会简化它:

mytable的:

CONDITION SIZE 
1          10
9          10
9          10
1          20
9          20
1          20
1          30

使用类似于

的查询
SELECT
  CASE WHEN CONDITION=1 THEN 'OK' ELSE 'BAD' END AS Status,
  SUM (CASE WHEN SIZE=10 THEN 1 ELSE 0 END) AS Small,
  SUM (CASE WHEN SIZE=20 THEN 1 ELSE 0 END) AS Medium,
  SUM (CASE WHEN SIZE=30 THEN 1 ELSE 0 END) AS Large,
FROM mytable GROUP BY Status

然后我们有了这个结果

Status    Small    Medium    Large
OK         1         2         1
BAD        2         1         0

获得的正确代码是什么:

Status    Small    Medium    Large
OK         1         2         1
BAD        2         1         0
TOTAL      3         3         1   

2 个答案:

答案 0 :(得分:2)

您可以在WITH ROLLUP条件中添加GROUP BY条款,如下所示:

SELECT
  CASE WHEN CONDITION=1 THEN 'OK' ELSE 'BAD' END AS Status,
  SUM (CASE WHEN SIZE=10 THEN 1 ELSE 0 END) AS Small,
  SUM (CASE WHEN SIZE=20 THEN 1 ELSE 0 END) AS Medium,
  SUM (CASE WHEN SIZE=30 THEN 1 ELSE 0 END) AS Large,
FROM mytable
GROUP BY Status WITH ROLLUP

这将产生如下结果集:

Status    Small    Medium    Large
OK         1         2         1
BAD        2         1         0
[NULL]     3         3         1 

您需要了解“状态”列中不存在任何Total值的行为。相反,“状态”列将具有NULL值,表示这是汇总的位置。

有关详细信息,请参阅此处的文档:http://dev.mysql.com/doc/refman/5.6/en/group-by-modifiers.html

答案 1 :(得分:0)

如果我理解正确,你需要在一个完整的查询中使用union,因为你不能同时以不同的方式聚合。

SELECT
  CASE WHEN CONDITION=1 THEN 'OK' ELSE 'BAD' END AS Status,
  SUM (CASE WHEN SIZE=10 THEN 1 ELSE 0 END) AS Small,
  SUM (CASE WHEN SIZE=20 THEN 1 ELSE 0 END) AS Medium,
  SUM (CASE WHEN SIZE=30 THEN 1 ELSE 0 END) AS Large,
FROM mytable GROUP BY Status

UNION

SELECT
  'Total' AS Status,
  SUM (CASE WHEN SIZE=10 THEN 1 ELSE 0 END) AS Small,
  SUM (CASE WHEN SIZE=20 THEN 1 ELSE 0 END) AS Medium,
  SUM (CASE WHEN SIZE=30 THEN 1 ELSE 0 END) AS Large,
FROM mytable