代码之家  ›  专栏  ›  技术社区  ›  Milan Pk

SQL Server:通过将表与大小写连接,将多行转换为多列:

  •  1
  • Milan Pk  · 技术社区  · 8 年前

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

    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\u访问表中引入一个字段,例如:

    首选结果:

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

    我加入了 Charge_Detail 表格收件人 PAT_VISIT 但是当我试图把 Patient_ID 字段来自 PAT\u访问 表,它不会显示。 任何帮助都将不胜感激! 非常感谢。

    1 回复  |  直到 8 年前
        1
  •  0
  •   Eray Balkanli    8 年前

    你能试试这个吗(我假设Patient\u Id是指患者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