2012-06-23 100 views
-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轉換 -

  1. HOW TO DO SUM ONLY IF [A.Actuals_Year]=[Current_Year]類似於Access查詢
  2. HOW TO GROUP BY [Current_Year]-1, tbl_CalendarYear.Current_Year類似

請訪問查詢建議。謝謝。

+2

爲什麼你將'Year'作爲'FLOAT'存儲?你能顯示樣本數據和期望的結果嗎?我不確定我明白'GROUP BY SomeYear-1'的含義... –

+0

當你已經用[Current_Year]分組時,爲什麼你需要通過'[Current_Year] -1'進行分組? –

回答

0

這似乎有點像一個奇怪的數據庫設計的,但是這可能會給你你需要的東西:

DECLARE @CurrentYear float 
DECLARE @PrevYear float 

SELECT @CurrentYear = MAX([Current_Year]) FROM tbl_CalendarYear 
SET @PrevYear = @CurrentYear - 1 

SELECT [PS] 
    ,@CurrentYear as CurrentYear 
    ,@PrevYear as PreviousYear 
    ,[Source] 
    ,[Program_Code] 
    ,SUM(CASE WHEN [Source]='Leasehold' AND [Actuals_Year] <> @CurrentYear THEN 
     [Amount] 
     ELSE 
      0 
     END) PrevYearAmount 
FROM Tbl_Actuals 
GROUP BY [PS] 
    ,[Source] 
    ,[Program_Code] 
ORDER BY [Program_Code]; 

關於問題(2),因爲@CurrentYear@PrevYear是變量,你不需要由他們組成。

我還注意到,您的訪問查詢正在求和Amount其中[Actuals_Year]<>[Current_Year]但在你的問題(1)你說它應該總結在哪裏[Actuals_Year]=[Current_Year]。我的答案在Access版本之後。

相關問題