2012-01-05 36 views
2

我正在使用Microsoft Sql Server 2008。 下面的查詢會讀取某些行,但可以從每個表中排列具有不同行的行。SQL Server 2008獨特行分組

select id1,c1,id2,c2,id3,c3 
from t1 
left join t2 on t2.fk = t1.pk 
left join t3 on t3.fk = t1.pk 
order by id3 

enter image description here

回答

2

你需要排序ID1,ID2和ID3

編輯:更新,添加順序欄

;WITH data AS 
(
    select id1,c1,id2,c2,id3,c3, 
      ROW_NUMBER() OVER (PARTITION BY id1, id2 ORDER BY id2) as id2seq, 
      ROW_NUMBER() OVER (PARTITION BY id1, id2, id3 ORDER BY id3) as id3seq  
    from t1 
    left join t2 on t2.fk = t1.pk 
    left join t3 on t3.fk = t1.pk 
) 
select id1, c1, id2, c2, id3, c3 
from data 
order by id1, id2seq, id3seq 

編輯:完成查詢確切的結果

;with data as( 
    select pid 
     , pname 
     , cid 
     , cname 
    from #t1 t1 
    left join #t2 t2 on t2.fk_pid = t1.pid 
), cte AS 
( 
    select pid 
      , eid 
      , ename 
    from #t1 t1 
     left join #t3 t3 on t3.fk_pid = t1.pid 
), combine AS 
(
    select d.pid 
     , pname 
     , cid 
     , cname 
     , ROW_NUMBER() over(partition by d.pid, cid order by cid) as seq 
     , eid 
     , ename 
     from data d join cte c on d.pid = c.pid 
) 
select pid, pname, cid, cname, eid, ename 
from combine 
order by pid, seq, cid 
+0

是啊,我已經試過了,但我已經得到了所需的輸出,請參見第2列,我需要先排序不同的行 – DON 2012-01-05 15:33:52

+0

我看到了問題。有沒有什麼能夠識別id2中的前5個,使其與第二個5不同?如果不是,那麼它們應該屬於一起,但從圖中可以看出,還有另外一個可以表示第一組和第二組的鍵 – Leons 2012-01-05 16:20:04

+0

是的,來自id2的5是該表的PK,並且它與來自id1的1聯合。 id1,c1 - table1,id2,c2 - table2,id3,c3 - table3。 table2和table3由來自table1的id1連接。希望你明白。 – DON 2012-01-05 16:28:41