2009-10-18 189 views
0

我有一個表晶格結構(高爾夫記分卡)如下:TSQL查詢樞轉

HoleID int 
CourseID int 
Par INT 
Distance INT 
LowIndex INT 
HighIndex INT 
Sequence INT (representing the sequence of the hole: 1, 2, 3, ... 18) 

這門課程有18個孔。

我想回轉到:

Hole,  1, 2, 3, ... 18 
Par,  X, X, X, ... X 
Distance, Y, Y, Y, ... Y 
LowIndex, Z, Z, Z, ... Z 
HighIndex, A, A, A, ... A 

我可以使用光標實現這一點,但有沒有更好的辦法?

+0

也許你能告訴我們你迄今爲止編寫的代碼?人們通常不喜歡只爲你寫代碼...... – 2009-10-18 07:57:58

+0

我可以使用光標方法編寫但可能有其他方法嗎? – dcpartners 2009-10-18 08:06:19

回答

1

TSQL直接支持pivoting。例如,看看herehere

+0

SQL2000不::( – 2009-10-18 08:17:08

+0

海報說他們在哪裏使用SQL Server 2000? – 2009-10-18 08:26:03

+0

我正在使用SQL 2005 – dcpartners 2009-10-18 08:36:54

1

你可以做

SELECT HoleID FROM Card WHERE HoleId =1 ,(SELECT HoleID FROM Card WHERE HoleId =2) , -- etc 

UNION 
SELECT Par FROM Card WHERE HoleId = 1, (SELECT Par FROM Card where HoleID=2). --etc 
UNION 
SELECT Distance FROM Card WHERE HoleId = 1, (SELECT Distance FROM Card where HoleID=2). --etc 
UNION 
SELECT LowIndex FROM Card WHERE HoleId = 1, (SELECT LowIndex FROM Card where HoleID=2). --etc 
UNION 
SELECT HIghIndex FROM Card WHERE HoleId = 1, (SELECT HighIndex FROM Card where HoleID=2). --etc 

如果你不顧一切地擺脫光標。

確保你讓所有的數據類型,通過鑄造或東西是相同的。

0

明白了只有第一部分......,會做。

select [1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18] 
from (Select Sequence, Par FROM holes WHERE CourseID=1) a 

PIVOT 
(
    Max(Par) 
    FOR [Sequence] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18]) 

) AS p 
0

完整列表:

select 'Par', [1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18] 
from (Select Sequence, Par FROM holes WHERE CourseID=1) a 

PIVOT 
(
    Max(Par) 
    FOR [Sequence] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18]) 

) AS p 

UNION 

select 'Distance', [1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18] 
from (Select Sequence, Distance FROM holes WHERE CourseID=1) a 

PIVOT 
(
    Max(Distance) 
    FOR [Sequence] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18]) 

) AS p 

UNION 


select 'LowIndex', [1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18] 
from (Select Sequence, LowIndex FROM holes WHERE CourseID=1) a 

PIVOT 
(
    Max(LowIndex) 
    FOR [Sequence] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18]) 

) AS p 

UNION 

select 'HighIndex', [1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18] 
from (Select Sequence, HighIndex FROM holes WHERE CourseID=1) a 

PIVOT 
(
    Max(HighIndex) 
    FOR [Sequence] IN ([1],[2],[3],[4],[5],[6],[7],[8],[9], [10], [11], [12], [13], [14], [15], [16], [17], [18]) 

) AS p