需要有关SQL查询的帮助(自联接)

时间:2013-11-26 04:03:36

标签: sql sql-server tsql

我有一张这样的表

MAIN ID CONTENT SUB ID

ABCD    ONE     888

ABCD    TWO     888

我希望查询结果像这样

MAIN ID SUB ID  CONTENT1  CONTENT2

ABCD    888      ONE         TWO    

1 个答案:

答案 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

子查询首先为每个要转动的结果content1content2等生成一个字段名称,如下所示:

| 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 |

演示:http://www.sqlfiddle.com/#!6/095bb/11