本文介紹了將行高效地透視/轉置為具有多列的列的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
假設我有如下數據:
Table
Num1 Type1 Code Group DA Account Value
1X2 GG XX1 INTS 1 123 75.00
1X2 GG XX1 INTS 1 234 100.00
我要做的是透視數據,使其如下所示:
Num1 Type1 Code Group DA 123 234
1X2 GG XX1 INTS 1 75.00 100.00
我不太確定如何使用Pivot來完成這樣的事情,但我確實嘗試了以下方法:
Select Num1,
Type1,
Code,
Group,
DA,
'123' = (Select Value from Table t2 where t1.num1 = t2.num1 and Account = 123 ),
'234' = (Select Value from Table t2 where t1.num1 = t2.num1 and Account = 234 )
From Table t1
但是,我收到的錯誤是:Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
在這種情況下,我將";Top 1";添加到每個子查詢:
Select Num1,
Type1,
Code,
Group,
DA,
'123' = (Select TOP 1 Value from Table t2 where t1.num1 = t2.num1 and Account = 123 ),
'234' = (Select TOP 1 Value from Table t2 where t1.num1 = t2.num1 and Account = 234 )
From Table t1
但是,盡管查詢現在返回兩行每個帳戶的金額,我并不完全理解TOP 1的用途,但基本上現在的數據如下:
Num1 Type1 Code Group DA 123 234
1X2 GG XX1 INTS 1 NULL 100.00
1X2 GG XX1 INTS 1 75.00 NULL
我想這還不錯,因為我可以對所有其他列執行MAX(123)
和MAX(234)
,最后得到1行。
有沒有更好的方法來解決這個問題?這可以通過Pivot實現嗎?
推薦答案
SELECT
[Num1],
[Type1],
[Code],
[Group],
[DA],
[123],
[234]
FROM
yourTable
PIVOT
(
MAX([value])
FOR [account] IN ([123], [234])
)
AS PivotTable
https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=7fbe16b9254aa5ee60a23e43eec9597f
這篇關于將行高效地透視/轉置為具有多列的列的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,