简体   繁体   English

将数据从行转换为列

[英]Transposing data into columns from rows

I have a data set where it goes something similar to this: 我有一个数据集,它类似于以下内容:

name    measure    status
john doe    blood pressure    iscompliant
john doe    Hba1c             notcompliant
jane doe    BMI               iscompliant
jane doe    blood pressure    notcompliant

I will have an unknown amount of measures to work with, so if there's a way to do this dynamically, that would be awesome. 我将要使用的措施数量未知,因此,如果有一种方法可以动态地做到这一点,那就太好了。 I'm looking for a result set like this: 我正在寻找这样的结果集:

name      blood pressure    Hba1c          BMI       
john doe  iscompliant       notcompliant   null   
jane doe  notcompliant      null           iscompliant

I couldn't find any examples that were able to tie two columns together like in my example with status and measure. 我找不到任何能够将两列连接在一起的示例,例如在我的状态和度量示例中。 I'm not sure if if I need to cross apply my data then pivot, or if I can pivot straight away. 我不确定是否需要交叉应用我的数据然后进行透视,或者我是否可以立即进行透视。 Any help is appreciated, thank you for your time. 感谢您的帮助,感谢您的宝贵时间。

edit: i am using sql server 2014 编辑:我正在使用SQL Server 2014

I eventually figured it out myself. 我终于自己弄明白了。 This isn't the real solution I am using, but a solution using the example data I posted above so people can reference this solution in the future. 这不是我正在使用的真正解决方案,而是使用我上面发布的示例数据的解决方案,以便以后人们可以参考该解决方案。

 DECLARE @DynamicPivotQuery AS NVARCHAR(MAX);
            DECLARE @ColumnName AS NVARCHAR(MAX);




--Get distinct values of the PIVOT Column 
            SELECT  @ColumnName = ISNULL(@ColumnName + ',' , '')
                    + QUOTENAME(Measure)
            FROM    ( SELECT DISTINCT
                                Measure
                      FROM      #temptable
                    ) AS qmdata;

--Prepare the PIVOT query using the dynamic 
            SET @DynamicPivotQuery = N'SELECT name, '
                + @ColumnName + '
                into workdb.dbo.qm_data_test
    FROM #temptable
    PIVOT(max(status)
          FOR measure IN (' + @ColumnName + ')) AS PVTTable';
--Execute the Dynamic Query
            EXEC sp_executesql @DynamicPivotQuery;

Once I had it in the workdb, I ran this to de-duplicate the data: 一旦将其放入工作数据库中,就可以运行该程序以消除重复数据:

SELECT  name
      ,MAX(measure1)
      ,MAX(measure2)
      ,MAX(measure3)
  FROM [workdb].[dbo].[qm_data_test]
  GROUP BY name

I am about to write the dynamic sql for the second query so I don't have to manually code each occurrence of MAX(ColumnName), so if a measure is added, my code will pick it up. 我将为第二个查询编写动态sql,因此不必手动为每次出现的MAX(ColumnName),编写代码MAX(ColumnName),因此,如果添加了一个度量,我的代码将对其进行选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM