将两个SQL Server查询合并为一个

时间:2015-01-29 12:58:27

标签: sql sql-server sql-server-2008

在数据库中运行查询有两个表,一个是实时的,一个是存档,但是我需要将两者中的数据相加,这里是我的查询示例。

SELECT     SUM(SOPOrderReturnLine.LineTotalValue) AS Value, CONVERT(date, SOPOrderReturnLine.DateTimeCreated) 
                  AS Date
FROM         SOPOrderReturnLine AS SOPOrderReturnLine 
WHERE     (SOPOrderReturnLine.AnalysisCode1 LIKE 'angela%') AND (CONVERT(date, SOPOrderReturnLine.DateTimeCreated) > DATEADD(day, - 15, GETDATE()))
GROUP BY CONVERT(date, SOPOrderReturnLine.DateTimeCreated)
ORDER BY Date

此查询对实时表中的数据求和,归档表与此结果完全相同,但称为SOPOrderReturnLineArch,将此合并到一个查询的最佳方法是什么,因此对于列值将是这个日期的两个表的总和,而不仅仅是现在的SOPOrderReturnLine。

2 个答案:

答案 0 :(得分:0)

使用UNION ALL组合两个表,然后像以前一样完成其余的工作:

SELECT     SUM(SOPOrderReturnLine.LineTotalValue) AS Value, CONVERT(date, SOPOrderReturnLine.DateTimeCreated) 
                  AS Date
FROM (SOPOrderReturnLine
      UNION ALL
      SOPOrderReturnLineArch
      ) AS SOPOrderReturnLine 
WHERE     (SOPOrderReturnLine.AnalysisCode1 LIKE 'angela%') AND (CONVERT(date, SOPOrderReturnLine.DateTimeCreated) > DATEADD(day, - 15, GETDATE()))
GROUP BY CONVERT(date, SOPOrderReturnLine.DateTimeCreated)
ORDER BY Date

或者使用两个结果执行UNION ALL:

SELECT     SUM(SOPOrderReturnLine.LineTotalValue) AS Value, CONVERT(date, SOPOrderReturnLine.DateTimeCreated) 
                  AS Date
FROM SOPOrderReturnLine 
WHERE     (SOPOrderReturnLine.AnalysisCode1 LIKE 'angela%') AND (CONVERT(date, SOPOrderReturnLine.DateTimeCreated) > DATEADD(day, - 15, GETDATE()))
GROUP BY CONVERT(date, SOPOrderReturnLine.DateTimeCreated)
UNION ALL
SELECT     SUM(SOPOrderReturnLine.LineTotalValue) AS Value, CONVERT(date, SOPOrderReturnLine.DateTimeCreated) 
                  AS Date
FROM SOPOrderReturnLineArc AS SOPOrderReturnLine 
WHERE     (SOPOrderReturnLine.AnalysisCode1 LIKE 'angela%') AND (CONVERT(date, SOPOrderReturnLine.DateTimeCreated) > DATEADD(day, - 15, GETDATE()))
GROUP BY CONVERT(date, SOPOrderReturnLine.DateTimeCreated)
ORDER BY Date

答案 1 :(得分:0)

在每个表中汇总结果,使用union all将它们组合在一起,然后重新聚合:

SELECT date, SUM(VALUE) as total_value
FROM ((SELECT CONVERT(date, orl.DateTimeCreated) as date,
              SUM(orl.LineTotalValue) AS Value
       FROM SOPOrderReturnLine AS orl 
       WHERE orl.AnalysisCode1 LIKE 'angela%') AND
             (CONVERT(date, orl.DateTimeCreated) > DATEADD(day, - 15, GETDATE()))
       GROUP BY CONVERT(date, orl.DateTimeCreated)
      ) UNION ALL
      (SELECT CONVERT(date, orl.DateTimeCreated) as date,
              SUM(orl.LineTotalValue) AS Value
       FROM SOPOrderReturnLine_archive AS orl 
       WHERE orl.AnalysisCode1 LIKE 'angela%') AND
             (CONVERT(date, orl.DateTimeCreated) > DATEADD(day, - 15, GETDATE()))
       GROUP BY CONVERT(date, orl.DateTimeCreated)
      ) 
     ) x
GROUP BY date
ORDER BY Date;

union all之前进行聚合为SQL Server提供了更多优化机会。这个总是总是比仅在union all之后进行聚合更快,但它可能是。