我有两个表,每个表都将自己的结果集生成为一行。我想将这些结果集合成一行。例如:
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的组合,这些组合将通过参数提供给查询。任何帮助将不胜感激。提前谢谢!
答案 0 :(得分: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;
现在,如果对两个表中是否存在year
和quarter
存在疑问,那么您可以使用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)
答案 1 :(得分:1)
您需要做的就是确定连接条件,即两个表中必须具有匹配值的列。在你的情况下,它看起来是年和季 所以你会写一些类似select * from Table_1 A Join Table_2 B ON A.year = B.year and A.quarter = B.quarter
答案 2 :(得分: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
(假设它们在相同位置具有相同的列)。