簡體   English   中英

重新排列動態SQL PIVOT中的列

[英]Reorder columns in dynamic SQL PIVOT

我正在使用動態SQL將行透視成列,以解決未知數目的列。 我正在使用SQL Server 16

DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(PatientDiagnosis) 
                from
                (
                  select 'Diagnosis'
                          + cast(row_number() over(partition by LbPatientId
                                                    order by LbPatientId) as varchar(10)) PatientDiagnosis
                  from #Diag50
                  --ORDER  BY ',' + Quotename(PatientDiagnosis) DESC
                ) d
                group by PatientDiagnosis
                 ORDER  BY ',' + Quotename(PatientDiagnosis)                    
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)'),1,1,'')

set @query = 'SELECT LbPatientId, ' + @cols + ' 
        from 
        (
            select LbPatientId, Diagnosis,
              ''Diagnosis''
                + cast(row_number() over(partition by LbPatientId
                                          order by LbPatientId) as varchar(10)) PatientDiagnosis
            from #Diag50
        ) x
        pivot 
        (
            MIN(Diagnosis)
            for PatientDiagnosis in (' + @cols + ')
        ) p '

execute sp_executesql @query;

這確實可以透視我的數據,但是“診斷”列的排序順序是錯誤的。

看起來像這樣(每個LbPatientId最多可能有50列)

LbPatientId|Diagnosis1|Diagnosis10|Diagnosis11|Diagnosis12...

----------- | ---------- | ----------- | ----------- | --- ----------- 1111 | Z95.5 | Z23 | Z13.89 | V85.1

我希望它看起來像這樣:

LbPatientId|Diagnosis1|Diagnosis2 |Diagnosis3 |Diagnosis4..

----------- | ---------- | ----------- | ----------- | --- ----------- 1111 | Z95.5 | Z23 | Z13.89

我已經嘗試過為排序列找到各種解決方案,但是仍然無法正常工作。 就訂單而言,真正重要的是列標題。 任何幫助,將不勝感激。

在查詢中包括row_number,並以此排序。

select @cols = STUFF((SELECT ',' + QUOTENAME(PatientDiagnosis) 
                from
                (
                  select 'Diagnosis'
                          + cast(row_number() over(partition by LbPatientId
                                                    order by LbPatientId) as varchar(10)) PatientDiagnosis,
                          row_number() over(partition by LbPatientId
                                                    order by LbPatientId)  PatientDiagnosisOrder
                  from #Diag50
                ) d
                group by PatientDiagnosis, PatientDiagnosisOrder
                ORDER  BY PatientDiagnosisOrder                    
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)'),1,1,'')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM