基于两个分组的SQL和

时间:2018-10-25 06:54:51

标签: sql oracle group-by sum

我有一张桌子

ID   | khk | ts
11AH | 10   | 2
11AH | 10   | 2
11AH | 9    | 1
22AH | 5    | 2
22AH | 5    | 3

我需要分组ID的sum(ts)(但仅当计数id大于2时才需要),并且仅当分组的khk计数大于1时才从中求和)

所以对于id 11AH,sum(ts)= 4(而不是5),对于22AH,什么都不是,因为它们只有两个。

我尝试这样的方法,但是不正确

select sum(ts),id from table group by id,khk having count(id)>2 and count(khk)>1;

3 个答案:

答案 0 :(得分:0)

尝试以下

DEMO

select * from
(select id,khk, sum(ts) as ts,(select count(id) from cte1 b where a.id=b.id) as cnt
from cte1 a 
group by id,khk 
having count(*)>1)X where cnt>2

输出:

id      khk  ts  cnt
11AH    10   4   3

答案 1 :(得分:0)

您可以尝试使用窗口功能

with cte
(
select id,khk,ts, count(*) over(partition by id order by id) as id_cnt,
count(*) over(partition by khk order by khk) as khk_cnt
) select id,khk,sum(ts)
 where id_cnt>2 and khk_cnt>1
 group by id,khk

答案 2 :(得分:0)

我建议使用分析功能而不是子查询:

select id, khk, sum_ts
from (select t.id, t.khk, sum(ts) as sum_ts,
             count(*) as cnt_id_khk, 
             count(*) over (partition by t.id) as cnt_id
      from t
      group by id, khk 
     ) t
where cnt_id_khk > 1 and cnt_id > 1