嗨,我试图使我的查询结果在每列1行中动态对齐。如果可能,请帮助我
比如这是我的桌子
id , names , comm , contrib
1 samp1 randtext 9
2 samp1 randtext 2
3 samp1 randtext 3
5 samp2 randtext 4
6 samp2 randtext 1
我想得到的结果是
names comm1 comm2 comm3 contrib1 contrib2 contrib3
samp1 randtext,randtext,randtext 9 , 2 , 3
samp2 randtext,randtext, 4 , 1 ,
谢谢你的帮助。
最佳答案
我们可以将ROW_NUMBER
与透视查询结合使用:
WITH cte AS (
SELECT *, ROW_NUMBER() OVER (PARTITION BY names ORDER BY id) rn
FROM your_table
)
SELECT
names,
MAX(CASE WHEN rn = 1 THEN comm END) comm1,
MAX(CASE WHEN rn = 2 THEN comm END) comm2,
MAX(CASE WHEN rn = 3 THEN comm END) comm3,
MAX(CASE WHEN rn = 1 THEN contrib END) contrib1,
MAX(CASE WHEN rn = 2 THEN contrib END) contrib2,
MAX(CASE WHEN rn = 3 THEN contrib END) contrib3
FROM cte
GROUP BY
names
ORDER BY
names;