这是一个奇怪的问题,我知道在SQL中不这样做会更容易,但它会让我的生活变得更轻松。
基本上我有一个列结果集,我需要将其转换为3列,而不是基于任何标准。
例如
1
2
3
4
5
6
7
成:
1 2 3
4 5 6
7
在这种情况下,它总是一个固定的3列结果。
目前我正在使用游标并插入表变量,这似乎有点可怕。必须有更好的方法。
由于
答案 0 :(得分:2)
试试这个:
declare @t table(n int)
insert @t(n) values(1),(2),(3),(4),(5),(6),(7),(8),(9),(10)
select [0],[1],[2]
from
(
select n
, (ROW_NUMBER() over (order by n) - 1) % 3 c
, (ROW_NUMBER() over (order by n) - 1) / 3 r
from @t
) x
pivot (max(n) for c in ([0], [1], [2])) p
答案 1 :(得分:1)
根据PIVOT operator尝试此解决方案:
DECLARE @MyTable TABLE (
ID INT PRIMARY KEY
);
INSERT @MyTable VALUES (11)
INSERT @MyTable VALUES (22)
INSERT @MyTable VALUES (33)
INSERT @MyTable VALUES (44)
INSERT @MyTable VALUES (55)
INSERT @MyTable VALUES (66)
INSERT @MyTable VALUES (77);
WITH RowsWithNum
AS (
SELECT *, ROW_NUMBER() OVER(ORDER BY ID) - 1 AS RowNum -- ORDER BY ID -> defines the order for numbering rows. ID values should be uniques. Thus results will be deterministic.
FROM @MyTable
), Groups
AS (
SELECT ID, RowNum % 3 AS ColumnID, RowNum / 3 AS GroupID
FROM RowsWithNum
)
SELECT *
FROM Groups AS x
PIVOT( MAX(x.ID) FOR x.ColumnID IN ([0], [1], [2]) ) AS pvt -- Comment this line to see what results return [Groups] common table expression
结果:
GroupID 0 1 2
------- --- ---- ----
0 11 22 33
1 44 55 66
2 77 NULL NULL
答案 2 :(得分:1)
这是可能的,但男人这是一个丑陋的要求。这个真的属于表示层,而不是sql。
WITH original As
(
SELEZCT MyColumn, row_number() over (order by MyColumn) as ordinal
FROM RestOfOriginalQueryHere
),
Grouped As
(
SELECT MyColumn, ordinal / 3 As row, ordinal % 3 As col
FROM original
)
SELECT o1.MyColumn, o2.MyColumn, o3.MyColumn
FROM grouped g1
LEFT JOIN grouped g2 on g2.row = g1.row and g2.col = 1
LEFT JOIN grouped g3 on g2.row = g1.row and g3.col = 2
WHERE g1.col = 0