我需要一些邏輯上的幫助來撰寫查詢。
這是設定。
create table main_table
(
id varchar(10) not null,
seq varchar(10) not null
)
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
)
insert into sub_table (id, seq)
values ('A1', '1'), ('A1', '2'), ('A2', '1');
我需要回傳所有記錄的查詢main_table,其中id的main_table比賽id的sub_table,但seq的main_table不匹配seq的sub_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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/361942.html
標籤:sql sql-server 查询语句
上一篇:TSQL-檢查是否存在
