Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
693 views
in Technique[技术] by (71.8m points)

sql server - SQL Transform Crosstab Pivot Data

I am using SQL Server 2008 and would like to transform my data such that:

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:

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.

I looked up PIVOT but I don't think this works here...what is this type of data transformation called? I don't think it's a crosstab...

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...