我需要一些邏輯上的幫助來撰寫查詢。這是設定。
create table main_table
(
id varchar(10) not null,
seq varchar(10) not null
)
GO
insert into main_table
(id, seq)
VALUES
('A1', '1'),
('A1', '2'),
('A1', '3'),
('A2', '1'),
('A2', '2'),
('A2', '3'),
('A3', '1'),
('A3', '2'),
('A3', '3');
GO
create table sub_table
(
id varchar(10) not null,
seq varchar(10) not null
)
GO
insert into sub_table
(id, seq)
VALUES
('A1', '1'),
('A1', '2'),
('A2', '1')
;
我需要一個查詢,從回傳的所有記錄MAIN_TABLE其中ID的MAIN_TABLE匹配的ID的子表,但序列的MAIN_TABLE不匹配序列的子表。
預期結果是
| ID | 序列 |
|---|---|
| A1 | 3 |
| A2 | 2 |
| A2 | 3 |
我的嘗試
select
a.id, a.seq
from main_table a
where exists
(select 1 from sub_table b
where a.id = b.id and a.seq != b.seq)
什么是正確的查詢來做到這一點。
uj5u.com熱心網友回復:
這是一種方法(小提琴)
SELECT a.id,
a.seq
FROM main_table a
JOIN sub_table b
ON a.id = b.id
GROUP BY a.id,
a.seq
HAVING MAX(CASE WHEN a.seq = b.seq THEN 1 ELSE 0 END) = 0
或者
SELECT a.id,
a.seq
FROM main_table a
WHERE a.id IN (SELECT b.id
FROM sub_table b)
AND NOT EXISTS (SELECT 1
FROM sub_table b
WHERE a.id = b.id
AND a.seq = b.seq)
uj5u.com熱心網友回復:
嘗試這個
select * from main_table M
inner join sub_table S on M.id = S.id
where M.seq <> S.seq
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358140.html
標籤:sql sql-server 查询语句
