选择对行求和的查询并将其作为列返回

时间:2014-04-03 21:45:19

标签: mysql

奇怪的问题......我知道。所以让我解释一下。

这是我的文本表

    quota     |    metric_id
     100      |        1
     20       |        2
     100      |        15
     50       |        1
     30       |        2
     20       |        15
     50       |        1
     200      |        2
     10       |        15

我想要一个返回以下

的SELECT语句
    id_1    |     id_2     |      id_15 
    200     |     250      |      130

以下是数据:

Column `id_1` is sum of the 3 rows where `metric_id=1`
Column `id_2` is sum of the 3 rows where `metric_id=2`
Column `id_15` is sum of the 3 rows where `metric_id=15`

任何帮助?

2 个答案:

答案 0 :(得分:0)

试试这个

select SUM(case when metric_id = 1 then quota END) id_1
       SUM(case when metric_id = 2 then quota END) id_2
       SUM(case when metric_id = 15 then quota END) id_15
FROM Table1

答案 1 :(得分:0)

一种可能的方法:

SELECT SUM(quota * (metric_id = 1)) AS id_1,
       SUM(quota * (metric_id = 2)) AS id_2,
       SUM(quota * (metric_id = 15)) AS id_15
FROM Table1

Demo。这很简单:metric_id = N对于具有该属性等于N的行为1,对于所有其他行为0。将quota乘以1是quota,乘以0 - 0,其余的是SUM()函数的简单任务。