如何在整数列上使用sum和avg等聚合函数,除了在Derby中排序后的前几行

时间:2015-04-18 13:18:57

标签: java sql derby

例如,我的表格如下:

+---------------------+
| TOTAL  NUMBER  NAME |
+---------------------+
| 10        5       A |
| 5         8       A |
| 21        32      A |
| 7         3       A |
| 7         3       B |
| 11        5       B |
| 5         8       B |
| 21        32      B |
+---------------------+

按NUMBER排序后:

+---------------------+
| TOTAL  NUMBER  NAME |
+---------------------+
| 7         3       A |
| 7         3       B |
| 10        5       A |
| 11        5       B |
| 5         8       A |
| 5         8       B |
| 21        32      A |
| 21        32      B |
+---------------------+

我只想要NAME分组的每组前两行的总和:

A  7+10=17
B  7+11=18

1 个答案:

答案 0 :(得分:1)

它将类似于:

select sum(total),name from
(select Total, name from 
table order by number where name = 'A' FETCH FIRST 2 ROWS ONLY 
 union select Total, name from 
table order by number where name = 'B' FETCH FIRST 2 ROWS ONLY )dt group by name

在派生的表格中,将按列号选择结果排序,外部查询将添加总值。

编辑:以下查询应该可以完成您的工作。

SELECT name,sum(total)
FROM   table s
WHERE 
        (
            SELECT  COUNT(*) 
            FROM    table t
            WHERE t.name = s.name AND 
                  t.number >= s.number
        ) <= 2
 group by name;