SQL 使用 case when 语句对多个 ID 按 ID 分组

SQL group by ID for multiple IDs using case when statements

我从具有多个代码(一年中多次)的患者列表开始,需要根据患者是否具有代码或代码组合将患者分成几组,不符合条件的患者被排除在外从列表中。我已经为每组代码创建了标志 (0,1)。 但问题是患者可以在另一行符合或不符合资格。我想要的是每个患者一行,然后我可以确定每个患者的适当组。以下是我尝试过的两种方法,但我不知道如何通过 ID and/or 汇总新列。

我试过的第一个代码:

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.%'
      )