繁体   English   中英

SQL查询:如何识别组差异

[英]SQL query: How to identify group differences

col1 col2 col3
组 1 亚组1 54
组 1 亚组1 31
组 1 亚组2 54
组 1 亚组2 55
组2 亚组3 40
组2 亚组3 41
组2 亚组4 40
组2 亚组4 41

每个组有多个子组,每个子组有多个值。

我需要过滤掉 col3 中具有相同值的组。 例如,group2 有值(40,41)

仅返回 group1 作为 subgroup1(54,31) 和 subgroup2(54,55) 在 col3 中共享不同的值 (31, 55)。 如何在 SQL 中实现这一点?

期望结果:

col1 col2 col3
组 1 亚组1 54
组 1 亚组1 31
组 1 亚组2 54
组 1 亚组2 55

您可以使用 string_agg()。 IE:

select col1, col2, string_agg(col3, ',')
from mytable
group by col1, col2;
CREATE TABLE mytable (
  col1 VARCHAR(10),
  col2 VARCHAR(10),
  col3 varchar(10)
);

INSERT INTO mytable
  (col1, col2, col3)
VALUES
  ('group1', 'subgroup1', '54'),
  ('group1', 'subgroup1', '31'),
  ('group1', 'subgroup2', '54'),
  ('group1', 'subgroup2', '55'),
  ('group2', 'subgroup3', '40'),
  ('group2', 'subgroup3', '41'),
  ('group2', 'subgroup4', '40'),
  ('group2', 'subgroup4', '41');

select col1, col2, string_agg(col3, ',')
from mytable
group by col1, col2;
col1 col2 (无列名)
组 1 亚组1 54,31
组 1 亚组2 54,55
组2 亚组3 40,41
组2 亚组4 40,41

DBFiddle 演示

编辑:根据您编辑和更改的要求:

with dummy as
(select col1, col2, string_agg(col3, ',') col3
from mytable
group by col1, col2
),
  unq as 
  (
select col3
from dummy
group by col3
having count(*) = 1
)
select * from dummy 
where exists (select col3 from unq where dummy.col3 = unq.col3);

DBFiddle 演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM