T-SQL: Joining result-sets horizontally(T-SQL:水平连接结果集)
问题描述
我有两个表,每个表都将自己的结果集作为一行生成.我想将这些结果集合并为一行.例如:
I have two tables, each which produce their own result-sets as a single row. I would like to join these result-sets into one single row. For example:
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 的组合上,这将通过参数输入到查询中.任何帮助将不胜感激.提前致谢!
The results are joined/pivoted onto the combination of Year and Quarter, which will be fed into the query via parameters. Any assistance would be greatly appreciated. Thanks in advance!
推荐答案
除非我遗漏了什么,看来你可以加入 year
/quarter
似乎没有必要对数据进行透视:
Unless I am missing something, it looks like you can just join the tables on the year
/quarter
there doesn't seem to be a need to pivot the data:
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 with Demo
现在如果有关于 year
和 quarter
是否存在于两个表中的问题,那么您可以使用 FULL OUTER JOIN代码>:
Now if there is a question on whether or not the year
and quarter
will exist in both tables, then you could use 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 with Demo
这篇关于T-SQL:水平连接结果集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:T-SQL:水平连接结果集


- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- SQL 临时表问题 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 更改自动增量起始编号? 2021-01-01