[英]Populating two rows for a specific condition using SQL query
SK | Code | SIG_Code | ID
---- ----------- ---------- ----
1 A S 1
1 B S 2
1 C M 3
2 A B 4
3 A S 5
4 A B 6
4 B B 7
考慮到上表,我想要同時具有“A”和“B”作為其代碼的記錄。 我嘗試編寫這樣的查詢,SELECT * FROM TABLE WHERE Code='A' and Code='B'。 但這似乎不起作用。 使用 IN 條件也沒有給我想要的 output。 有人可以幫我建立這個查詢嗎?
謝謝你。
您可以使用聚合:
select sk
from t
where code in ('A', 'B')
group by sk
having count(*) = 2;
這假設沒有重復。 如果允許重復,則使用count(distinct code) = 2
。
您可以使用解析 function 如下獲取整個記錄:
select * from
(
select t.*,
count(distinct code) over (partition by sk) as cnt
from yout_table t
where code in ('A', 'B')
)
where cnt = 2
上面的查詢將返回 sk=1 的 2 條記錄(代碼為 A 和 B)和 sk=4 的 2 條記錄
如果您想要包含 A 和 B 的 id 的所有記錄(sk = 1 的 3 個記錄),那么您可以使用以下代碼:
select * from
(
select t.*,
count(distinct case when code in ('A', 'B') then code end)
over (partition by sk) as cnt
from yout_table t
)
where cnt = 2
i) 嘗試使用子查詢
select* from #table a
where code in( 'A', 'B')
and SIG_Code in (select SIG_Code from #table b where code in ('B') and a.sk=b.sk)
ii) 使用大小寫和計數功能嘗試以下查詢。
select sk, code, SIG_Code,ID from
(
select t.*,
count(case when code = 'b' then 'a' end) over (partition by sk) as cnt
from #table t
where code in ('A', 'B')
) a
where cnt = 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.