简体   繁体   English

SQL转换交叉表数据透视表

[英]SQL Transform Crosstab Pivot Data

I am using SQL Server 2008 and would like to transform my data such that: 我正在使用SQL Server 2008,并且希望将数据转换为:

Dataset: 数据集:

ID   Item  Columns  Result
1     1      X       A
2     1      Y       B
3     1      Z       C
4     2      X       D
5     2      Y       E
6     2      Z      NULL
7     3      X       F
8     3      Y       G
9     3      Z       H

Results Desired: 所需结果:

Item   X   Y   Z
 1     A   B   C
 2     D   E  NULL
 3     F   G   H

At this time, I am doing the following, then pasting the columns I need into Excel: 目前,我正在执行以下操作,然后将所需的列粘贴到Excel中:

Select * from thisTable where Column=X
Select * from thisTable where Column=Y
Select * from thisTable where Column=Z

However, not all of the rows match up to can can't just smack the tables side by side. 但是,并非所有匹配的行都不能仅仅并排击打表。 For columns without a Result, I'd like NULL to show up to fill in the rows to make them all the same number of records. 对于没有Result的列,我希望显示NULL来填充行以使它们都具有相同数量的记录。

I looked up PIVOT but I don't think this works here...what is this type of data transformation called? 我查了一下PIVOT,但我认为这在这里不起作用...这种数据转换称为什么类型? I don't think it's a crosstab... 我不认为这是交叉表...

Thanks! 谢谢!

You can do a crosstab using conditional aggregation: 您可以使用条件聚合来执行交叉表:

SELECT
    Item,
    [X] = MAX(CASE WHEN [Columns] = 'X' THEN Result END),
    [Y] = MAX(CASE WHEN [Columns] = 'Y' THEN Result END),
    [Z] = MAX(CASE WHEN [Columns] = 'Z' THEN Result END)
FROM thisTable
GROUP BY Item

use PIVOT 使用PIVOT

select  *
from    (
            select  Item, Columns, Result
            from    thisTable 
        ) t
pivot   (
            max (Result)
            for Columns in (X, Y, Z)
        ) p

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

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