1

我有以下查询:

select

(select Sum(Stores) from XYZ where Year = '2013' and Month = '8' )
-
(select Sum(SalesStores) from ABC where Year = '2013' and Month = '8') as difference

在上面的查询中,年和月也是表的列。

我想知道是否有办法运行相同的查询,以便在一年中的每个月都运行它?

4

5 回答 5

2
;WITH Months(Month) AS
(
    SELECT 1 
    UNION ALL
    SELECT Month + 1
    FROM Months
    where Month < 12
)


SELECT '2013' [Year], m.Month, COALESCE(SUM(Stores), 0) - COALESCE(SUM(SalesStores), 0) [Difference]
FROM months m
LEFT JOIN XYZ x ON m.Month = x.Month
LEFT JOIN ABC a ON a.Month = m.Month

GROUP BY m.Month
于 2013-11-12T19:59:18.380 回答
2

如果有几个月没有数据/行XYZABC表格,那么我会使用FULL OUTER JOIN

SELECT ISNULL(x.[Month], y.[Month]) AS [Month],
       ISNULL(x.Sum_Stores, 0) - ISNULL(y.Sum_SalesStores, 0) AS Difference
FROM   
(
    SELECT [Month], Sum(Stores) AS Sum_Stores 
    FROM   XYZ 
    WHERE  [Year] = '2013' 
    GROUP BY [Month]
) AS x
FULL OUTER JOIN
(
    SELECT [Month], Sum(SalesStores) AS Sum_SalesStores 
    FROM   ABC 
    WHERE  [Year] = '2013' 
    GROUP BY [Month]
) AS y ON x.[Month] = y.[Month]
于 2013-11-12T20:09:43.797 回答
1

你可以GROUP BY在你的内部交易中使用,然后运行一个连接,如下所示:

SELECT left.Month, (left.sum - COALESCE(right.sum, 0)) as difference
FROM (
    SELECT Month, SUM(Stores) as sum
    FROM XYZ WHERE Year = '2013'
    GROUP BY Month
) left
LEFT OUTER JOIN (
    SELECT Month, SUM(Stores) as sum
    FROM ABC WHERE Year = '2013'
    GROUP BY Month
) right ON left.Month = right.Months

注意使用COALESCE. SUM如果表中没有月份的记录,它可以让您保留第一个值ABC

于 2013-11-12T19:59:25.333 回答
0

在以下示例中,将 UNION ALL 运算符与 CTE 结合使用

;WITH cte AS
 (SELECT SUM(Stores) AS Stores, [Month]
  FROM dbo.XYZ
  WHERE [Year] = '2013'
  GROUP BY [Month]      
  UNION ALL
  SELECT -1.00 * SUM(SalesStores), [Month]
  FROM dbo.ABC      
  WHERE [Year] = '2013'
  GROUP BY [Month]
  )
  SELECT [Month], SUM(Stores) AS Difference
  FROM cte  
  GROUP BY [Month]

演示SQLFiddle

于 2013-11-12T22:21:02.633 回答
0
  ;WITH Months(Month) AS
    (
        SELECT 1 
        UNION ALL
        SELECT Month + 1
        FROM Months
        where Month < 12
    )

    SELECT Months. Month ,
(select isnull(Sum(Stores),0) from XYZ where Year = '2013' and Month = Months.Month) - (select isnull(Sum(SalesStores),0) from ABC where Year = '2013' and Month =Months.Month) as difference
    FROM Months
于 2013-11-14T11:45:41.577 回答