2013-11-26 65 views
2

我有這樣需要幫助的SQL查詢(自聯接)

MAIN ID CONTENT SUB ID 

ABCD ONE  888 

ABCD TWO  888 

一個表,我想查詢的結果是這樣的

MAIN ID SUB ID CONTENT1 CONTENT2 

ABCD 888  ONE   TWO  
+1

共享查詢 – SK2185

+0

更像是一個數據透視查詢。 –

+1

您可以通過像這樣的PIVOT: http://stackoverflow.com/questions/2542982/pivot-function-in-sql-server-2008 –

回答

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

+0

解決我的問題,謝謝! – user3034814