简体   繁体   English

SQL group by ID for multiple IDs using case when statements

[英]SQL group by ID for multiple IDs using case when statements

I started with a list of patients with multiple codes (at multiple times of year) and need to split the patients into groups based on if they have a code or combo of codes and those that don't qualify are excluded from the list.我从具有多个代码的患者列表(一年中的多个时间)开始,需要根据患者是否有代码或代码组合将患者分组,而那些不符合条件的将被排除在列表之外。 I have already created flags (0,1) for each set of codes.我已经为每组代码创建了标志 (0,1)。 But the problem is that a patient can qualify or disqualify on another row.但问题是患者可以在另一行符合或取消资格。 What I'd like is one row per patient which I can then determine the appropriate group per patient.我想要的是每个患者一行,然后我可以确定每个患者的适当组。 Below is the two ways I've tried but I can't figure out how to roll up by ID and/or the new column.以下是我尝试过的两种方法,但我不知道如何按 ID 和/或新列进行汇总。

1st code I tried:我试过的第一个代码:

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

2nd code I tried:我试过的第二个代码:

,(case when (HL2='1' and dm='0' and ht='0') then 1 else 0 end) as exclude

HAVE

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

You seem to want conditional aggregation.您似乎想要条件聚合。 Your question is a little hard to follow, but the idea is:你的问题有点难以理解,但这个想法是:

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