SQL语句按ID组合使用多个ID,使用case when语句

问题描述 投票:0回答:1

我首先列出了具有多个代码的患者列表(每年多次),需要根据患者是否具有代码或代码组合以及不符合条件的患者将其分为几类。 。我已经为每组代码创建了标志(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   

WANT

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
sql case-when id
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.%'
      )
© www.soinside.com 2019 - 2024. All rights reserved.