我正在使用Microsoft 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
答案 0 :(得分: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