have a table as below -
COL1 | COL2 | COL3
1 1 1
1 1 2
1 2 0
1 2 1
2 3 1
2 3 2
2 4 0
2 4 1
3 1 0
3 2 0
.
.
.
I want to select COL1 where all COL2 have sum(COL3) is > 0. If I am sure there are 20 distinct values in COL2, Then how can i pull all COL1 values that have all 20 COL2 filled with COL3 > 0. So the end result should be
COL1 | COL2 | COL3
1 1 3
1 2 1
2 3 3
2 4 1
I have tried a lot of ways to do this but no success.
答案 0 :(得分:2)
Just use group by
and having
.
select col1,col2,sum(col3)
from tbl
group by col1,col2
having sum(col3)>0
答案 1 :(得分:0)
I use a CTE
and a Group by
with a where
condition
;WITH CTE as (
select COL1,COL2,SUM(COL3) as COL3 FROM table1
Group By
COL1,COL2
)
select * from CTE
where COL3>0
答案 2 :(得分:0)
select t1.*
from yourTable t1
inner join
(
select t.col1
from
(
select col1, col2, sum(col3) as col_sum
from yourTable
group by col1, col2
) t
group by t.col1
having sum(case when t.col_sum = 0 then 1 else 0 end) = 0
) t2
on t1.col1 = t2.col1
答案 3 :(得分:0)
只需将col2分组并检查它是否大于0
select col1,col2,sum(col3)
from tbl
group by col2
having sum(col3)>0
答案 4 :(得分:0)
看看下面是否为您提供了您所追求的结果。它是从派生(?)表中选择col1,col2和col3之和,该表排除了0的col3:
select col1, col2, sum(col3)
from
(
select col1, col2, col3 from tbl where col3 <> 0
) as ds
group by col3