将两个SQL SELECT查询结果合并为一个查询和一个结果

时间:2015-06-19 12:54:59

标签: sql sql-server

我在合并两个选择查询的结果时面临问题 我在sql中执行了以下代码,您可以尝试

CREATE TABLE #a(a_id int, is_active bit, cr_date date)
CREATE TABLE #b(b_id int, a_id int, cr_date date)

INSERT INTO #a(a_id,is_active, cr_date)
VALUES(1,1,GETDATE()),(2,0,GETDATE()),(3,1,GETDATE()),(4,0,GETDATE()),(5,0,GETDATE())

INSERT INTO #b(b_id,a_id,cr_date)
VALUES(1,1,GETDATE()),(2,1,GETDATE()),(3,4,GETDATE()),(4,4,GETDATE()),(5,4,GETDATE()),(6,4,GETDATE())


CREATE TABLE #c(c_id int, is_active bit, cr_date date)
CREATE TABLE #d(d_id int, c_id int, cr_date date)

INSERT INTO #c(c_id,is_active, cr_date)
VALUES(1,1,GETDATE()),(2,0,GETDATE()),(3,1,GETDATE()),(4,0,GETDATE()),(5,0,GETDATE())

INSERT INTO #d(d_id,c_id,cr_date)
VALUES(1,1,GETDATE()),(2,1,GETDATE()),(3,4,GETDATE()),(4,4,GETDATE()),(5,4,GETDATE()),(6,4,GETDATE())



DECLARE @startDate date;
DECLARE @endDate date;
set @startDate='2012-10-26';
set @endDate=GETDATE();

SELECT 
'#b= '+CAST(COUNT(b.b_id) AS VARCHAR)   b_COUNT,
'#a = '+CAST(COUNT(a.a_id) AS VARCHAR)  a_COUNT  
FROM #a as a LEFT JOIN #b as b    ON a.a_id = b.a_id AND a.is_active = 0
WHERE CONVERT(VARCHAR(10), a.cr_date, 111)   BETWEEN @STARTDATE AND @ENDDATE

SELECT 
'#d= '+CAST(COUNT(d.d_id) AS VARCHAR)   d_COUNT,
'#c = '+CAST(COUNT(c.c_id) AS VARCHAR)  c_COUNT  
FROM #c as c LEFT JOIN #d as d    ON c.c_id = d.c_id AND c.is_active = 0
WHERE CONVERT(VARCHAR(10), c.cr_date, 111)   BETWEEN @STARTDATE AND @ENDDATE

for dropping tables 
DROP TABLE #a
DROP TABLE #b
DROP TABLE #c
DROP TABLE #d

我得到了两个选择查询的以下结果

Result of two select queries which are mentioned in question

现在,我想合并选择查询的两个结果,但我不能。

任何人都可以告诉我如何合并两个查询以获得输出中的单个结果

2 个答案:

答案 0 :(得分:4)

您可以使用UNIONUNION ALL

示例:

SELECT N'A' as col
UNION ALL
SELECT N'B' as col

您可以使用ALL按原样保留结果。即使可能有重复。 ALL会更快。

如果您遗漏ALL,将检查查询是否有重复项。

答案 1 :(得分:0)

使用UNION:

SELECT 
'#b= '+CAST(COUNT(b.b_id) AS VARCHAR)   b_COUNT,
'#a = '+CAST(COUNT(a.a_id) AS VARCHAR)  a_COUNT  
FROM #a as a LEFT JOIN #b as b    ON a.a_id = b.a_id AND a.is_active = 0
WHERE CONVERT(VARCHAR(10), a.cr_date, 111)   BETWEEN @STARTDATE AND @ENDDATE
UNION
SELECT 
'#d= '+CAST(COUNT(d.d_id) AS VARCHAR)   d_COUNT,
'#c = '+CAST(COUNT(c.c_id) AS VARCHAR)  c_COUNT  
FROM #c as c LEFT JOIN #d as d    ON c.c_id = d.c_id AND c.is_active = 0
WHERE CONVERT(VARCHAR(10), c.cr_date, 111)   BETWEEN @STARTDATE AND @ENDDATE