我有一张表格结构(高尔夫记分卡)如下:
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 :(得分:1)
答案 1 :(得分: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
如果你不顾一切地摆脱光标。
确保通过强制转换或其他方式使所有数据类型相同。
答案 2 :(得分: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
答案 3 :(得分: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