[英]SQL group by ID for multiple IDs using case when statements
我從具有多個代碼的患者列表(一年中的多個時間)開始,需要根據患者是否有代碼或代碼組合將患者分組,而那些不符合條件的將被排除在列表之外。 我已經為每組代碼創建了標志 (0,1)。 但問題是患者可以在另一行符合或取消資格。 我想要的是每個患者一行,然后我可以確定每個患者的適當組。 以下是我嘗試過的兩種方法,但我不知道如何按 ID 和/或新列進行匯總。
我試過的第一個代碼:
SELECT
a.*
into file_2
from (select code,ID, 'HL2' as grp_1
from file_1
where (code like '%I60.%' or code like '%I61.%')
and (code not like '%I20.%' and code not like '%I21.%'
and code not like '%I63.%' and code not like '%I64.%'
and code not like '%I70.%') a
我試過的第二個代碼:
,(case when (HL2='1' and dm='0' and ht='0') then 1 else 0 end) as exclude
有
ID CV CA HT DM HL PA HL1 HL2 exclude
1003 0 0 0 0 1 0 0 1 1
1096 0 0 0 0 1 0 0 1 1
1096 0 0 0 1 0 0 0 0 0
1096 0 0 1 0 0 0 0 0 0
1196 0 0 0 0 0 1 0 0 0
1196 0 0 1 0 0 0 0 0 0
1196 1 0 0 0 0 0 0 0 0
1196 0 0 0 0 1 0 0 1 1
想
ID CV CA HT DM HL PA HL1 HL2 exclude
1003 0 0 0 0 1 0 0 1 1
1096 0 0 1 1 1 0 0 1 0
1196 1 0 1 0 1 1 0 1 0
您似乎想要條件聚合。 你的問題有點難以理解,但這個想法是:
select id, max(cv) as cv,
. . .
(case when max(HL2) = 1 and max(dm) = 0 and max(ht) = 0) then 1 else 0 end) as exclude
from file_1
where (code like '%I60.%' or code like '%I61.%') and
(code not like '%I20.%' and code not like '%I21.%' and
code not like '%I63.%' and code not like '%I64.%' and
code not like '%I70.%'
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.