SQL Server组合结果集

时间:2012-12-13 16:29:37

标签: sql-server-2008 multiple-resultsets

我正在尝试将两个不同查询的结果集合并到一个结果集中。这可能没有使用存储过程,可能使用WITH关键字吗?

采取以下案例:

SELECT * FROM student WHERE graduation_year = 2013 -- returns 140 rows
SELECT * FROM student WHERE graduation_year = 2014 -- returns 130 rows

请忽略在这里暗示OR的明显解决方案,因为我忽略了复杂的动态约束,只是为了说明我的观点。

我想从每个查询单独中获取结果,并将它们合并为一个结果集。

3 个答案:

答案 0 :(得分:2)

您可以在两个查询之间使用UNION ALL

SELECT *, '2013' Source
FROM student 
WHERE graduation_year = 2013 
UNION ALL
SELECT *, '2014' Source
FROM student 
WHERE graduation_year = 2014 

请参阅SQL Fiddle with Demo

如果您需要识别该行来自哪个数据集,我添加了一个名为source的字段,如果不需要,可以将其排除。

如果你想在临时表中使用它,你可以使用这样的:

select *
into #temp
from
(
  SELECT *, '2013' Source
  FROM student 
  WHERE graduation_year = 2013 
  UNION ALL
  SELECT *, '2014' Source
  FROM student 
  WHERE graduation_year = 2014 
) src


select * from #temp

请参阅SQL Fiddle with Demo

答案 1 :(得分:2)

您可以使用UNION ALL

SELECT *
FROM student 
WHERE graduation_year = 2013 
UNION ALL
SELECT *
FROM student 
WHERE graduation_year = 2014 

答案 2 :(得分:1)

SELECT * FROM student WHERE graduation_year = 2013 -- returns 140 rows
Union All -- Retrieves all results from both recordsets including both duplicates
SELECT * FROM student WHERE graduation_year = 2014 -- returns 130 rows

SELECT * FROM student WHERE graduation_year = 2013 -- returns 140 rows
Union -- Retrieves all results from both recordsets discarding duplicates
SELECT * FROM student WHERE graduation_year = 2014 -- returns 130 rows