![](/img/trans.png)
[英]How to query 2 tables in sql server with many to many relationship to identify differences
[英]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 |
編輯:根據您編輯和更改的要求:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.