简体   繁体   English

SQL查询:如何识别组差异

[英]SQL query: How to identify group differences

col1 col1 col2 col2 col3 col3
group1组 1 subgroup1亚组1 54 54
group1组 1 subgroup1亚组1 31 31
group1组 1 subgroup2亚组2 54 54
group1组 1 subgroup2亚组2 55 55
group2组2 subgroup3亚组3 40 40
group2组2 subgroup3亚组3 41 41
group2组2 subgroup4亚组4 40 40
group2组2 subgroup4亚组4 41 41

Each group has a number of subgroups and each subgroup has a number of values.每个组有多个子组,每个子组有多个值。

I need to filter out the group that has the same value in col3.我需要过滤掉 col3 中具有相同值的组。 For example, group2 has values(40,41)例如,group2 有值(40,41)

only return group1 as subgroup1(54,31) and subgroup2(54,55) shares different values(31, 55) in col3.仅返回 group1 作为 subgroup1(54,31) 和 subgroup2(54,55) 在 col3 中共享不同的值 (31, 55)。 How can I achieve this in SQL?如何在 SQL 中实现这一点?

Desire result:期望结果:

col1 col1 col2 col2 col3 col3
group1组 1 subgroup1亚组1 54 54
group1组 1 subgroup1亚组1 31 31
group1组 1 subgroup2亚组2 54 54
group1组 1 subgroup2亚组2 55 55

You could use string_agg().您可以使用 string_agg()。 ie: 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 col1 col2 col2 (No column name) (无列名)
group1组 1 subgroup1亚组1 54,31 54,31
group1组 1 subgroup2亚组2 54,55 54,55
group2组2 subgroup3亚组3 40,41 40,41
group2组2 subgroup4亚组4 40,41 40,41

DBFiddle demo DBFiddle 演示

EDIT: According to your edited and changed requirement:编辑:根据您编辑和更改的要求:

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 demo DBFiddle 演示

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

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