多个GROUP BY和选择值取决于第一个GROUP BY的结果

时间:2014-09-28 11:49:37

标签: sql sqlite greatest-n-per-group

我得到了以下数据库表:

combination_id  |   weight  |   group   |   std
-------------------------------------------------
    1           |   50      |   3       |   7   
    2           |   30      |   3       |   19
    3           |   30      |   3       |   19
    4           |   25      |   4       |   7

我按标准列对条目进行分组,并总结重量列的值:

SELECT SUM(weight) as weight_sum, group, std FROM weight_table 
WHERE combination_id IN (1, 2, 3) 
GROUP BY group, std
ORDER BY weight_sum DESC;

结果如下:

    weight  |   group   |   std
-----------------------------------------------
    60      |   3       |   19  
    50      |   3       |   7
    25      |   4       |   7

现在我想要第二个GROUP BY,但仅限于列,并总结权重列。结果中 std 列的值应为具有最高权重的条目的 std 列的值以及上次查询中的相同组。 因此,对于 3 组,我希望标准选择 19 ,因为 60 是最高的 3

组的重量
    weight  |   group   |   std
-----------------------------------------------
    110     |   3       |   19  
    25      |   4       |   7

我怎样才能做到这一点? 我正在使用sqlite 3。

1 个答案:

答案 0 :(得分:1)

我想你想要这个:

SELECT SUM(weight) as weight_sum, group, max(std) as std FROM weight_table 
WHERE combination_id IN (1, 2, 3) 
GROUP BY group
ORDER BY weight_sum DESC;

换句话说,不要将此视为“多个组别”。可以将其视为单个聚合,您可以同时获得权重之和和std的最大值。

编辑:

我似乎误解了这个问题。这对SQL lite来说有点痛苦。这是一种方法:

with w as (
      SELECT SUM(weight) as weight_sum, group, std
      FROM weight_table 
      WHERE combination_id IN (1, 2, 3) 
      GROUP BY group, std
     ),
     wmax as (
      SELECT group, MAX(weight_sum) as maxws
      FROM w
      GROUP BY gruop
     )
select w.group, sum(w.weight_sum) as weight_sum,
       max(case when w.weight_sum = wmax.weight_sum then std end) as std
from w left join
     wmax
     on w.group = wmax.group
group by w.group
order by weight_sum DESC;