具有相同fk到列的多行

qqrboqgw  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(351)

我需要编写一个t-sql查询来转换、转置数据集的任何正确术语,如下所示。

Table a
ID, CategoryID, Col1, Col2, Col3, Col4, Col5, Col6
1,     1,       val1, val2, val3, val4, val5, val6
2,     1,       val1, val2, val3, val4, val5, val6
3,     1,       val1, val2, val3, val4, val5, val6
4,     2,       val1, val2, val3, val4, val5, val6
5,     2,       val1, val2, val3, val4, val5, val6
6,     2,       val1, val2, val3, val4, val5, val6

CategoryID, Col1, Col2, Col3, Col4, Col5, Col6, Col1, Col2, Col3, Col4, Col5, Col6, Col1, Col2, Col3, Col4, Col5, Col6
1, val1, val2, val3, val4, val5, val6, val1, val2, val3, val4, val5, val6, val1, val2, val3, val4, val5, val6
2, val1, val2, val3, val4, val5, val6, val1, val2, val3, val4, val5, val6, val1, val2, val3, val4, val5, val6

所以对于表a中的每个categoryid,取所有列。以categoryid作为主键生成行,并将所有列值放在彼此后面

1l5u6lss

1l5u6lss1#

如果预先知道每个类别的最大行数,则有一个选项使用 row_number() 和条件聚合。
下面是如何对每个类别有三个行的三列执行此操作

select
    categoryID,
    max(case when rn = 1 then col1 end) col1_1,
    max(case when rn = 1 then col2 end) col2_1,
    max(case when rn = 1 then col3 end) col3_1,
    max(case when rn = 2 then col1 end) col1_2,
    max(case when rn = 2 then col2 end) col2_2,
    max(case when rn = 2 then col3 end) col3_2,
    max(case when rn = 3 then col1 end) col1_3,
    max(case when rn = 3 then col2 end) col2_3,
    max(case when rn = 3 then col3 end) col3_3
from (
    select t.*, row_number() over(partition by categoryID order by id) rn
    from mytable t
) t
group by categoryID

相关问题