[英]Help needed in pivoting (SQL Server 2005)
我有一張桌子
ID Grps Vals
--- ---- -----
1 1 1
1 1 3
1 1 45
1 2 23
1 2 34
1 2 66
1 3 10
1 3 17
1 3 77
2 1 144
2 1 344
2 1 555
2 2 11
2 2 22
2 2 33
2 3 55
2 3 67
2 3 77
所需的輸出是
ID Record1 Record2 Record3
--- ------- ------- -------
1 1 23 10
1 3 34 17
1 45 66 77
2 144 11 55
2 344 22 67
2 555 33 77
我已經嘗試過(使用while循環),但是程序運行緩慢。 我被要求通過使用基於SET的方法來這樣做。 到目前為止,我的方法是
SELECT ID,[1] AS [Record1], [2] AS [Record2], [3] as [Record3]
FROM (
Select
Row_Number() Over(Partition By ID Order By Vals) records
,*
From myTable)x
PIVOT
(MAX(vals) FOR Grps IN ([1],[2],[3])) p
但這是行不通的。
任何人都可以幫助解決此問題。(SQL SERVER 2005)
你快到了! 我要做的就是將必要的列添加到Partition By和Order By子句中,並且可以正常工作:
SELECT ID,[1] AS [Record1], [2] AS [Record2], [3] as [Record3]
FROM (
Select
Row_Number() Over(Partition By id, grps Order By id, grps, vals) records
,*
From myTable)x
PIVOT
(MAX(vals) FOR Grps IN ([1],[2],[3])) p
一個不涉及使用PIVOT的簡單方法將是:
;With ItemGroups As
(
Select Id, Grps, Vals
, Row_Number() Over ( Partition By Id, Grps Order By Vals ) As RowNum
From myTable
)
Select Id
, Max( Case When Grps = 1 Then Vals End )
, Max( Case When Grps = 2 Then Vals End )
, Max( Case When Grps = 3 Then Vals End )
From ItemGroups
Group By Id, RowNum
Order By Id
這可能不適用於您,但是如果您使用while循環之類的話...
while( x<Total.length() ){
....do something
}
you should declare Total.length outside of the loop assigned to a variable...
int spoon= Total.length();
while( x< spoon ){
....do something
}
要不然
您每次循環運行時都會計算總數Total.length()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.