说我有一个看起来像这样的表:
Person Table
ID AccountID Name
1 6 Billy
2 6 Joe
3 6 Tom
4 8 Jamie
5 8 Jake
6 8 Sam
我有两个问题,我知道他们自己工作:
Select Name Group1 from person where accountid = 6
Select Name Group2 from person where accountid = 8
但我希望单个结果集看起来像这样:
Group1 Group2
Billy Jamie
Joe Jake
Tom Same
答案 0 :(得分:3)
我同意你应该做这个客户端。但它可以在T / SQL中完成:
select G1.Name as Group1
, G2.Name as Group2
from (
select row_number() over (order by ID) as rn
, *
from Group
where AccountID = 6
) as G1
full outer join
(
select row_number() over (order by ID) as rn
, *
from Group
where AccountID = 8
) as G2
on G1.rn = G2.rn
order by
coalesce(G1.rn, G2.rn)
答案 1 :(得分:3)
您可以使用row_number()
为每行分配不同的值,然后使用FULL OUTER JOIN
加入两个子查询:
select t1.group1,
t2.group2
from
(
select name group1,
row_number() over(order by id) rn
from yourtable
where accountid = 6
) t1
full outer join
(
select name group2,
row_number() over(order by id) rn
from yourtable
where accountid = 8
) t2
on t1.rn = t2.rn;