将多行连接为一行,并按日期分组

时间:2019-07-16 14:39:11

标签: sql sql-server

我的代码有问题:我想将多行连接为一个字符串或文本,然后按日期排序

select distinct 
    no_rm,
    riwayat_penyakit,
    berat_badan,
    keluhan,
    stuff((select distinct ',' + diagnosa
           from tb_rekam_medis
           where no_rm = 'RM001' 
           for xml path('')), 1, 1, '') as diagnosa,
    stuff((select distinct ',' + tindakan
           from tb_rekam_medis
           where no_rm = 'RM001' 
           for xml path('')), 1, 1, '') as tindakan,
    id_dokter,
    poli,
    tgl_pemeriksaan
from
    tb_rekam_medis
where 
    no_rm = 'RM001'

here is the schema of my table

here the sample data I have

我希望该数据为:

"B37.9, B37.3" for date 2019-07-16 and
"B37.9" for date 2019-07-09

1 个答案:

答案 0 :(得分:0)

我找到了答案

select distinct a.no_rm,
            a.riwayat_penyakit,
            a.berat_badan,
            a.keluhan,
            STUFF((select distinct ',' + diagnosa
                   from tb_rekam_medis
                   where no_rm = 'RM001'
                     and tgl_pemeriksaan = a.tgl_pemeriksaan FOR XML PATH ('')), 1, 1, '') as diagnosa,
            stuff((select distinct ',' + tindakan
                   from tb_rekam_medis
                   where no_rm = 'RM001'
                     and tgl_pemeriksaan = a.tgl_pemeriksaan FOR XML PATH ('')), 1, 1, '') as tindakan,
            a.id_dokter,
            a.poli,
            a.tgl_pemeriksaan

来自tb_rekam_medis a 其中no_rm ='RM001'