0

假设我有一张如下所示的表格:

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
4

2 回答 2

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)
于 2013-03-22T18:59:53.020 回答
3

您可以使用row_number()为每一行分配一个不同的值,然后使用 aFULL 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;

请参阅带有演示的 SQL Fiddle

于 2013-03-22T19:00:45.023 回答