我有一个数据列表,我想显示它们而不管其顺序如何,而是按列的特定顺序显示,例如3
id
1
2
3
4
5
6
7
8
9
10
11
12
13
14
id1 id2 id3
1 6 11
2 7 12
3 8 13
4 9 14
5 10 NULL
答案 0 :(得分:0)
您可以使用窗口函数和条件聚合:
select max(case when seqnum % 3 = 1 then id end),
max(case when seqnum % 3 = 2 then id end),
max(case when seqnum % 3 = 0 then id end)
from (select t.*,
row_number() over (order by (select null)) as seqnum
from t
) t
group by (seqnum - 1) / 3
答案 1 :(得分:0)
这很棘手。一种方法是对ROW_NUMBER
使用两次调用,一个用于行位置,另一个用于列位置。这里的逻辑是,每行都属于一个组,该组随着id
增加5的倍数而翻转,而该列由id
值代表的5的倍数确定。
WITH cte AS (
SELECT id,
(ROW_NUMBER() OVER (ORDER BY id) - 1) / 5 AS rn1,
(ROW_NUMBER() OVER (ORDER BY id) - 1) % 5 AS rn2
FROM yourTable
)
SELECT
rn2,
MAX(CASE WHEN rn1 = 0 THEN id END) AS id1,
MAX(CASE WHEN rn1 = 1 THEN id END) AS id2,
MAX(CASE WHEN rn1 = 2 THEN id END) AS id3
FROM cte
GROUP BY
rn2
ORDER BY
rn2;