我有一张这样的表
MAIN ID CONTENT SUB ID
ABCD ONE 888
ABCD TWO 888
我希望查询结果像这样
MAIN ID SUB ID CONTENT1 CONTENT2
ABCD 888 ONE TWO
答案 0 :(得分:2)
您可以使用PIVOT
功能:
select
*
from (
select
[main id],
[sub id],
[content],
'content' + cast(
row_number() over (partition by [main id],[sub id] order by content)
as varchar(5)) as contentIX
from
table1
) T
pivot (max(Content) for contentIX in (content1,content2)) as content
子查询首先为每个要转动的结果content1
,content2
等生成一个字段名称,如下所示:
| MAIN ID | SUB ID | CONTENT | CONTENTIX |
|---------|--------|---------|-----------|
| ABCD | 888 | ONE | content1 |
| ABCD | 888 | TWO | content2 |
然后外部查询在CONTENTIX
列上执行转移以获得最终结果:
| MAIN ID | SUB ID | CONTENT1 | CONTENT2 |
|---------|--------|----------|----------|
| ABCD | 888 | ONE | TWO |