Oracle SQL根据其他列值对一列进行分组

时间:2015-11-09 10:26:55

标签: sql oracle

我的表:

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

2 个答案:

答案 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)

您的表格及其数据:

enter image description here

此代码块解决了您的问题,请检查它:

select mt.con_ref ,sum(mt.sal) from mytable mt where mt.col_ref = 'NON' and not exists (select * from mytable mt1 where mt1.con_ref = mt.con_ref and mt1.col_ref <> 'NON') group by mt.con_ref ,mt.col_ref

并输出:

enter image description here