如何将两个查询组合成多列

时间:2013-03-11 10:35:44

标签: sql sql-server-2008

我想结合2个查询来制作一个像这样的结果

Sandi | schemaid | value | Sandi | schemaid | value
100   | 2883     | 12324 | 200   | 2886     | 3456
120   | 2882     | 435   | 220   | 2887     | 555 
130   | 2881     | 3456  | 230   | 2888     | 333 

,查询是:

select y.Sandi , y.schemaid,y.value from tbl_schema y
where y.idx=1

select y.Sandi , y.schemaid,y.value from tbl_schema y
where y.idx=2

你能帮助我吗?

2 个答案:

答案 0 :(得分:1)

由于您希望单独的idx数据显示在列而不是行中,因此您可以使用include row_number()并加入row_number上的单独查询,类似于:

select
  q1.Sandi q1_Sandi,
  q1.schemaid q1_schemaid,
  q1.value q1_value,
  q2.sandi q2_Sandi,
  q2.schemaid q2_schema_id,
  q2.value q2_value
from
(
  select sandi, schemaid, value,
    row_number() over (order by sandi) rn
  from tbl_schema
  where idx = 1
) q1
full outer join
(
  select sandi, schemaid, value,
    row_number() over (order by sandi) rn
  from tbl_schema
  where idx = 2
) q2
  on q1.rn = q2.rn

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

由于您在两个查询中使用相同的表(tbl_schema), for given ids (idx) 我认为您可以使用full outer join,如下所示:

select y.Sandi, y.schemaid, y.value, x.Sandi_, x.schemaid_, x.value_  
from tbl_schema y full outer join tbl_schema x
       on y.idx + 1 = x.idx
where y.idx = 1 and x.idx = 2
相关问题