3

我正在尝试将两个不同查询的结果集组合成一个结果集。这是否可能使用存储过程,也许使用 WITH 关键字?

举个例子:

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

请忽略此处建议 OR 的明显解决方案,因为我忽略了复杂的动态约束,只是为了说明我的观点。

我想分别从每个查询中获取结果并将它们组合成一个结果集。

4

3 回答 3

2

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

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

请参阅带有演示的 SQL Fiddle

如果您需要识别该行来自哪个数据集,我添加了一个名为 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

于 2012-12-13T16:34:42.190 回答
2

您可以使用UNION ALL

SELECT *
FROM student 
WHERE graduation_year = 2013 
UNION ALL
SELECT *
FROM student 
WHERE graduation_year = 2014 
于 2012-12-13T16:35:39.560 回答
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
于 2012-12-13T16:33:08.630 回答