내 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);
나의 현재 쿼리가
+------+-------+------------+-----------------+--------------+
| Year | Month | Sum_Stores | Sum_SalesStores | Sum_Products |
+------+-------+------------+-----------------+--------------+
| 2013 | | | | |
| 2013 | | | | |
| 2013 | | | | |
+------+-------+------------+-----------------+--------------+
을 반환
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;
입니다
내가 원하는 것은 지난 달과의 차이를 보여주는 열을 쿼리에 추가하는 것입니다. 아래 그림과 같이. 예 : Sum_Stores 옆의 차이은 지난 달의 Sum_Stores와 이번 달의 차이를 보여줍니다. 이 같은
뭔가 :
+------+-------+------------+-----------------+-----|-----|---+-----------------
| Year | Month | Sum_Stores |Diff | Sum_SalesStores |Diff | Sum_Products |Diff|
+------+-------+------------+-----|------------+----|---- |----+--------------|
| 2013 | | | | | | | |
| 2013 | | | | | | | |
| 2013 | | | | | | | |
+------+-------+------------+-----|------------+--- |-----|----+---------| ----
이 사람이 내 목표를 실현하려이를 수정하는 방법을 말해 줄 수.
당신은 여기 비슷한 질문에 대한 답변의 약간 수정 된 버전을 사용할 수 알려 : http://stackoverflow.com/questions/20527213/sql-query - 생성 - 열과 산술 표현식/20528571 # 20528571 – Mike