我有我的SQL表和查詢中值的差異,如下圖所示:SQL查詢來發現從上月
CREATE TABLE #ABC([Year] INT, [Month] INT, Stores INT);
CREATE TABLE #DEF([Year] INT, [Month] INT, SalesStores INT);
CREATE TABLE #GHI([Year] INT, [Month] INT, Products INT);
INSERT #ABC VALUES (2013,1,1);
INSERT #ABC VALUES (2013,1,2);
INSERT #ABC VALUES (2013,2,3);
INSERT #DEF VALUES (2013,1,4);
INSERT #DEF VALUES (2013,1,5);
INSERT #DEF VALUES (2013,2,6);
INSERT #GHI VALUES (2013,1,7);
INSERT #GHI VALUES (2013,1,8);
INSERT #GHI VALUES (2013,2,9);
INSERT #GHI VALUES (2013,3,10);
我當前的查詢是
I have @Year and @Month as parameters , both integers , example @Year = '2013' , @Month = '11'
SELECT T.[Year],
T.[Month]
-- select the sum for each year/month combination using a correlated subquery (each result from the main query causes another data retrieval operation to be run)
,
(SELECT SUM(Stores)
FROM #ABC
WHERE [Year] = T.[Year]
AND [Month] = T.[Month]) AS [Sum_Stores],
(SELECT SUM(SalesStores)
FROM #DEF
WHERE [Year] = T.[Year]
AND [Month] = T.[Month]) AS [Sum_SalesStores],
(SELECT SUM(Products)
FROM #GHI
WHERE [Year] = T.[Year]
AND [Month] = T.[Month]) AS [Sum_Products]
FROM (
-- this selects a list of all possible dates.
SELECT [Year],
[Month]
FROM #ABC where [Year] = @Year and [Month] = @Month
UNION
SELECT [Year],
[Month]
FROM #DEF where [Year] = @Year and [Month] = @Month
UNION
SELECT [Year],
[Month]
FROM #GHI where [Year] = @Year and [Month] = @Month) AS T;
它返回
+------+-------+------------+-----------------+--------------+
| Year | Month | Sum_Stores | Sum_SalesStores | Sum_Products |
+------+-------+------------+-----------------+--------------+
| 2013 | | | | |
| 2013 | | | | |
| 2013 | | | | |
+------+-------+------------+-----------------+--------------+
我想要做的是在查詢中添加更多列,以顯示與上個月的差異。如下所示。 示例:Sum_Stores旁邊的Diff顯示Sum_Stores從上個月到本月的差異。
事情是這樣的:
+------+-------+------------+-----------------+-----|-----|---+-----------------
| Year | Month | Sum_Stores |Diff | Sum_SalesStores |Diff | Sum_Products |Diff|
+------+-------+------------+-----|------------+----|---- |----+--------------|
| 2013 | | | | | | | |
| 2013 | | | | | | | |
| 2013 | | | | | | | |
+------+-------+------------+-----|------------+--- |-----|----+---------| ----
誰能告訴我怎麼可以修改這個才達到我的目標。
你可以使用答案略加修改版本到你類似的問題在這裏:http://stackoverflow.com/questions/20527213/sql-query -to-創建柱,用算術表達式/ 20528571#20528571 – Mike