我的表:
con_ref col_ref sal
1 NON 25
1 COL 36
1 COL 12
1 NON 13
2 NON 25
2 NON 6
2 NON 33
3 COL 42
3 NON 51
4 NON 63
4 NON 31
4 NON 15
我想将Con_ref
列的上述数据分组,其中col_ref
值仅为' NON
'。因此,如果col_ref
同时具有' NON
'和' COL
'这应该排除。
期望的输出:
CON_REF sum(SAL)
2 64
4 109
答案 0 :(得分:1)
这样的事情:
sum((rowSums(df == 1) > 0) & (rowSums(df == 2) > 0))
## [1] 4
ETA:与不使用with sample_data as (select 1 con_ref, 'NON' col_ref, 25 sal from dual union all
select 1 con_ref, 'COL' col_ref, 36 sal from dual union all
select 1 con_ref, 'COL' col_ref, 12 sal from dual union all
select 1 con_ref, 'NON' col_ref, 16 sal from dual union all
select 2 con_ref, 'NON' col_ref, 25 sal from dual union all
select 2 con_ref, 'NON' col_ref, 6 sal from dual union all
select 2 con_ref, 'NON' col_ref, 33 sal from dual union all
select 3 con_ref, 'COL' col_ref, 42 sal from dual union all
select 3 con_ref, 'NON' col_ref, 51 sal from dual union all
select 4 con_ref, 'NON' col_ref, 63 sal from dual union all
select 4 con_ref, 'NON' col_ref, 31 sal from dual union all
select 4 con_ref, 'NON' col_ref, 15 sal from dual)
-- end of mimicking a table called sample_data with data in it
select con_ref,
sum(sal)
from sample_data
group by con_ref
having count(case when col_ref != 'NON' then 1 end) = 0;
CON_REF SUM(SAL)
---------- ----------
2 64
4 109
的请求相同的结果(N.B.这适用于Oracle;我不知道它是否适用于其他平台):
GROUP BY
答案 1 :(得分:0)