0

我有两个表,每个表都将自己的结果集作为一行生成。我想将这些结果集加入一行。例如:

SELECT *
FROM Table 1
WHERE Year = 2012 AND Quarter = 1

结果:

Year  Quarter  Name  State  Mail
2012  1        Bob   NY     bob@gmail

查询 #2:

SELECT *
FROM Table 2
WHERE Year = 2012 AND Quarter = 1

结果:

Year  Quarter  Name  State  Mail
2012  1        Greg  DC     greg@gmail

所需的结果集:

SELECT *
FROM Table 3
WHERE Year = 2012 AND Quarter = 1

Year  Quarter  T1Name  T1State  T1Mail     T2Name  T2State  T2Mail
2012  1        Bob     NY       bob@gmail  Greg    DC       greg@gmail

结果被连接/透视到 Year 和 Quarter 的组合,这将通过参数输入到查询中。任何帮助将不胜感激。提前致谢!

4

3 回答 3

3

除非我遗漏了某些东西,否则您似乎可以只加入year/上的表格,quarter似乎不需要旋转数据:

select t1.year, 
  t1.quarter,
  t1.name t1Name,
  t1.state t1State,
  t1.mail t1Mail,
  t2.name t2Name,
  t2.state t2State,
  t2.mail t2Mail
from table1 t1
inner join table2 t2
  on t1.year = t2.year
  and t1.quarter = t2.quarter
where t1.year = 2012
  and t1.quarter = 1;

请参阅带有演示的 SQL Fiddle

year现在,如果对两个表中是否存在and存在疑问quarter,那么您可以使用 a FULL OUTER JOIN

select coalesce(t1.year, t2.year) year, 
  coalesce(t1.quarter, t2.quarter) quarter,
  t1.name t1Name,
  t1.state t1State,
  t1.mail t1Mail,
  t2.name t2Name,
  t2.state t2State,
  t2.mail t2Mail
from table1 t1
full outer join table2 t2
  on t1.year = t2.year
  and t1.quarter = t2.quarter
where (t1.year = 2012 and t1.quarter = 2)
  or  (t2.year = 2012 and t2.quarter = 2)

请参阅带有演示的 SQL Fiddle

于 2013-05-29T18:12:36.730 回答
1

您需要做的就是确定连接条件,即必须在两个表中具有匹配值的列。在您的情况下,它看起来是 Year 和 Quarter
,因此您可以编写类似 select * from Table_1 A Join Table_2 B ON A.year=B.year 和 A.quarter=B.quarter

于 2013-05-29T18:14:32.277 回答
0

如果您有两个查询返回一行,则可以使用以下命令将它们放在一个结果行中cross join

select t1.Year, t1.Quarter, T1.Name, T1.State, T1.Mail, T2.Name, T2.State, T2.Mail
from (SELECT *
      FROM Table 1
      WHERE Year = 2012 AND Quarter = 1
     ) t1 cross join
     (SELECT *
      FROM Table 2
      WHERE Year = 2012 AND Quarter = 1
     ) t2

如果您希望它们位于单独的行中,则使用union all(假设它们在相同位置具有相同的列)。

于 2013-05-29T18:24:09.573 回答