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

上記のクエリでは、Year と Month もテーブルの列です。

同じクエリを実行して、その年のすべての月に対して実行する方法があるかどうか知りたいですか?

4

5 に答える 5

2

XYZまたはABCテーブル内にデータ/行がない月がある場合は、次を使用し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 に答える
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 に答える
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

の使用に注意してくださいCOALESCESUMテーブルにその月のレコードがない場合に備えて、最初の値を保持できますABC

于 2013-11-12T19:59:25.333 に答える
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 に答える