我需要为下面的查询转换数据,当前数据在3列中.Case1,case2 check image1 current result 我需要Month作为每个月下的column和case1,case2数据。检查图像2 expected result
select
month(pe.contact_date) as Month,
sum (case when pt.sex_c=1 and pe.ENC_TYPE_C = '3' then 1 else 0 end) as case1,
sum (case when pt.sex_c=1 and pe.ENC_TYPE_C = '101' then 1 else 0 end) as case2
from
patient pt, pat_enc pe
where
pt.PAT_ID=pe.PAT_ID
group by month (pe.CONTACT_DATE)
order by month (pe.CONTACT_DATE)
答案 0 :(得分:0)
您要做的事情似乎是“转置”操作。这是一种可能有用的通用方法,因为我不知道你是否有'pivot / unpivot'操作。
select
case when month(pe.CONTACT_DATE) % 2 = 1 then 'case1' else 'case2' end) as "??"
min(case when month(pe.CONTACT_DATE) = 1 then case1 else case2 end) as "1"
min(case when month(pe.CONTACT_DATE) = 2 then case1 else case2 end) as "2"
...
min(case when month(pe.CONTACT_DATE) = 12 then case1 else case2 end) as "12"
from <table> pe
group by month(pe.CONTACT_DATE) % 2
答案 1 :(得分:0)
这应该按照您需要的方式转动数据
select case when pt.sex_c=1 and pe.ENC_TYPE_C = '3' then 'case1'
when pt.sex_c=1 and pe.ENC_TYPE_C = '101' then 'case2'
end as casetype,
count(case when month(pe.contact_date) = 1 then 1 end) as [1],
count(case when month(pe.contact_date) = 2 then 1 end) as [2],
count(case when month(pe.contact_date) = 3 then 1 end) as [3],
count(case when month(pe.contact_date) = 4 then 1 end) as [4],
count(case when month(pe.contact_date) = 5 then 1 end) as [5],
count(case when month(pe.contact_date) = 6 then 1 end) as [6],
count(case when month(pe.contact_date) = 7 then 1 end) as [7],
count(case when month(pe.contact_date) = 8 then 1 end) as [8],
count(case when month(pe.contact_date) = 9 then 1 end) as [9],
count(case when month(pe.contact_date) = 10 then 1 end) as [10],
count(case when month(pe.contact_date) = 11 then 1 end) as [11],
count(case when month(pe.contact_date) = 12 then 1 end) as [12]
from patient pt
join pat_enc pe on pt.pat_id = pe.pat_id
group by case when pt.sex_c=1 and pe.ENC_TYPE_C = '3' then 'case1' when pt.sex_c=1 and pe.ENC_TYPE_C = '101' then 'case2' end