简体   繁体   English

行到列的部分转置

[英]Partial transpose of rows to columns

The question is very simple , but I am having troubles with realization. 问题很simple ,但是我在实现上遇到麻烦。

The current table looks like this: 当前表如下所示:

ID  Value

A   1
A   2
A   3
B   1
B   2
C   1

And i need it like this: 我需要这样:

ID Value1 Value2 Value3 Value...
A   1      2      3      NULL
B   1      2      NULL   NULL
C   1     NULL    NULL   NULL

If the value columns are a known\\reasonable set range ie 1-5 you can do something like the following: 如果值列是已知的\\合理的设置范围(即1-5),则可以执行以下操作:

Select ID, 
    MAX(CASE WHEN Value = 1 Then 1 Else Null End) as Value1,
    MAX(CASE WHEN Value = 2 Then 2 Else Null End) as Value2,
    MAX(CASE WHEN Value = 3 Then 3 Else Null End) as Value3,
    MAX(CASE WHEN Value = 4 Then 4 Else Null End) as Value4,
    MAX(CASE WHEN Value = 5 Then 5 Else Null End) as Value5
From Table
Group By ID

If you don't know the number of columns at the outset ie they are dynamic you will then have to write a dynamic sql pivot. 如果您一开始不知道列数,即它们是动态的,则必须编写一个动态sql数据透视表。 There are plenty of stack examples showing this: 有很多堆栈示例显示了这一点:

OK, with your help, and a help from a friend, i solved the problem like this. 好的,在您的帮助下以及在朋友的帮助下,我解决了这样的问题。

Select ROW_NUMBER() 
        OVER (PARTITION BY Field1 
        ORDER BY Field1) 
        AS order_num, Field1, Value
into #tab1
from Source_Table
Order by Field1


Select * 
from #tab1
    PIVOT
        (Max(Value)  
            FOR order_num IN ([1], [2], [3], [4], [5])) AS PVT


drop table #tab1

I still have to fully understand how it works, but it works. 我仍然必须完全了解它是如何工作的,但是它是有效的。 I hope it helps someone else too. 我希望它也可以帮助其他人。

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

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