【问题标题】:Reorder columns in dynamic SQL PIVOT对动态 SQL PIVOT 中的列重新排序
【发布时间】:2020-01-15 13:55:14
【问题描述】:

我正在使用动态 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

我已经尝试了各种用于排序列的解决方案,但仍然无法正常工作。就顺序而言,这里的列标题确实很重要。任何帮助将不胜感激。

【问题讨论】:

  • 这是因为它是按字母顺序排序的,因为 RowNumber 与 'Diagnosis' 连接,你想按数字排序

标签: sql dynamic pivot


【解决方案1】:

在您的查询中包含 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,'')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    • 1970-01-01
    • 2014-06-12
    • 2023-04-09
    • 2012-06-03
    相关资源
    最近更新 更多