-1
我試圖將MS Access查詢轉換爲SQL Sever存儲過程,但是存在兩個無關表中的求和和分組字段的問題。它可以在MS Access中執行,但我無法在SQL Server存儲過程中複製它。將訪問查詢轉換爲SQL Server存儲過程
這裏的MS Access查詢我想轉換 -
MS Access查詢
SELECT Tbl_Actuals.PS
, [tbl_CalendarYear.Current_Year]-1 AS [Previous Year]
, tbl_CalendarYear.Current_Year
, Tbl_Actuals.Source
, Tbl_Actuals.Program_Code
, IIf([Source]="Leasehold",Sum(IIf([Actuals_Year]<>[Current_Year], ([Amount]),Null)),Null) AS PrevYearAmount
FROM Tbl_Actuals, tbl_CalendarYear
GROUP BY Tbl_Actuals.PS
, [tbl_CalendarYear.Current_Year]-1
, tbl_CalendarYear.Current_Year
, Tbl_Actuals.Source
, Tbl_Actuals.Program_Code
ORDER BY Tbl_Actuals.Program_Code;
下面是上面的SQL Server存儲過程的轉換。
declare @CurrentYear float
declare @PrevYear float
SET @CurrentYear=(SELECT [Current_Year] FROM tbl_CalendarYear)
SET @PrevYear= (SELECT [Current_Year] -1 FROM tbl_CalendarYear)
SELECT PS
, @CurrentYear as CurrentYear
, @PrevYear as PreviousYear
, A.Source
, A.Program_Code
, CASE WHEN (A.Source='Leasehold') THEN SUM(A.Amount) -- HOW TO DO SUM ONLY IF [A.Actuals_Year]=[Current_Year] similar to Access Query END AS PrevYearAmount
FROM Tbl_Actuals A
GROUP BY PS
, Source
, Program_Code -- HOW TO GROUP BY [Current_Year]-1, tbl_CalendarYear.Current_Year similar to Access Query
ORDER BY Program_Code;
這裏是我的問題,與SQL轉換 -
- HOW TO DO SUM ONLY IF
[A.Actuals_Year]=[Current_Year]
類似於Access查詢 - HOW TO GROUP BY
[Current_Year]-1, tbl_CalendarYear.Current_Year
類似
請訪問查詢建議。謝謝。
爲什麼你將'Year'作爲'FLOAT'存儲?你能顯示樣本數據和期望的結果嗎?我不確定我明白'GROUP BY SomeYear-1'的含義... –
當你已經用[Current_Year]分組時,爲什麼你需要通過'[Current_Year] -1'進行分組? –