繁体   English   中英

SQL group by ID for multiple IDs using case when statements

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM