减少两个UNION查询的输出,当前产生的行太多

时间:2016-12-14 05:16:58

标签: sql-server merge union

SQL Server:这是我的基本查询。我无法弄清楚如何正确地做出这个"结果"每个商店/日期只显示一行,两个查询分别填写第3列和第4列。现在结果是每个商店/日期给我2行,在相对列中为NULL。每个商店/日期应该只有一行,偶尔会有NULL剩余的第三列。

DECLARE @START DATETIME, @END DATETIME
SET @END   = CAST(CAST(GETDATE() AS DATE) AS DATETIME) + '03:00'
SET @START = @END - 7

SELECT 
    @START [From], @END [To]

SELECT 
    DivisionName, DateClosed, COUNT(OrderId) AS PREDATED, NULL AS DAYOF 
FROM 
    (SELECT 
         o.OrderId, DivisionName, DateCreated, 
         CONVERT(Date, DateClosed) [DateClosed]   
     FROM 
         POS.Orders o WITH(NOLOCK)
     JOIN 
         POS.OrderDetails od WITH(NOLOCK) ON o.OrderId = od.OrderId
     JOIN 
         Directory.Divisions d WITH(NOLOCK) ON o.DivisionId = d.DivisionId
     WHERE 
         DateClosed BETWEEN @START AND @END AND DateCreated < @START) t
 GROUP BY 
     DivisionName, DateClosed

 UNION

 SELECT 
     DivisionName, DateClosed, NULL AS PREDATED, COUNT(OrderID) AS DAYOF
 FROM 
     (SELECT 
          o.OrderId, DivisionName, DateCreated, 
          CONVERT(Date,DateClosed)[DateClosed]
      FROM 
          POS.Orders o WITH(NOLOCK)
      JOIN 
          POS.OrderDetails od WITH(NOLOCK) ON o.OrderId = od.OrderId
      JOIN 
          Directory.Divisions d WITH(NOLOCK) ON o.DivisionId = d.DivisionId
      WHERE 
          DateClosed BETWEEN @START AND @END AND DateCreated >= @START) s
GROUP BY 
    DivisionName, DateClosed

SQL results

1 个答案:

答案 0 :(得分:2)

您可以使用这样的结构:

Max Latency

我没有您的示例数据,但您可以使用这样的查询:

;WITH t as (
    <your query>
) 
SELECT DivisionName, DateClosed, MAX(PREDATED) AS PREDATED, MAX(DAYOF) AS DAYOF 
FROM t 
GROUP BY DivisionName, DateClosed;