SQL Server:通过使用CASE连接表,将多行转换为多列:

时间:2018-02-08 16:41:04

标签: sql sql-server case

我有这个查询,它给了我完美的结果:

select vst_int_id,
max(case when seq = 1 then chg_dtl_int_id end) chg1,
max(case when seq = 2 then chg_dtl_int_id end) chg2,
max(case when seq = 3 then chg_dtl_int_id end) chg3,
max(case when seq = 4 then chg_dtl_int_id end) chg4,
max(case when seq = 5 then chg_dtl_int_id end) chg5
from (
       select c.vst_int_id, c.chg_dtl_int_id,   
       row_number() over(partition by c.vst_int_id order by chg_dtl_int_id) seq

       from CHARGE_DETAIL c
       inner join PAT_VISIT b ON b.vst_int_id = c.vst_int_id
       where c.vst_int_id = '14568778'
)d
group by vst_int_id

结果:

vst_int_id  |     chg1   |  chg2     |    chg3   |  chg4    |     chg5
14568778    |    23340   |  2334     |    2334   |   2490   |     2110

我想从PAT_VISIT表中引入一个字段,例如:

首选结果:

vst_int_id  |   chg1|    chg2   |   chg3     |   chg4   |  chg5 | Patient_ID
14568778    |  23340|    2334   |   4534     | 2490     | 2110  | 0012456

我已将Charge_Detail表加入PAT_VISIT表,但当我尝试从Patient_ID表中提取PAT_VISIT字段时,它将不会显示。 任何帮助将不胜感激! 谢谢。

1 个答案:

答案 0 :(得分:0)

你可以尝试一下吗(我假设Patient_Id是指患者身份的确切列名):

select vst_int_id,
max(case when seq = 1 then d.chg_dtl_int_id end) chg1,
max(case when seq = 2 then d.chg_dtl_int_id end) chg2,
max(case when seq = 3 then d.chg_dtl_int_id end) chg3,
max(case when seq = 4 then d.chg_dtl_int_id end) chg4,
max(case when seq = 5 then d.chg_dtl_int_id end) chg5,
p.Patient_ID
from (
       select c.vst_int_id, c.chg_dtl_int_id,   
       row_number() over(partition by c.vst_int_id order by chg_dtl_int_id) seq
       from CHARGE_DETAIL c
       where c.vst_int_id = '14568778'
) d
inner join PAT_VISIT p ON p.vst_int_id = d.vst_int_id
group by d.vst_int_id, p.Patient_ID