将Access查询转换为SQL Server存储过程

时间:2012-06-23 18:27:35

标签: sql-server

我正在尝试将MS Access查询转换为SQL Sever存储过程,但是对两个不相关的表中的字段进行求和和分组存在问题。可以在MS Access中执行此操作,但我无法在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. 如果[A.Actuals_Year]=[Current_Year]类似于访问查询
  2. ,该怎么办?
  3. 如何分组[Current_Year]-1, tbl_CalendarYear.Current_Year类似于访问查询
  4. 请告知。谢谢。

1 个答案:

答案 0 :(得分: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是变量,因此您无需按其分组。

我还注意到您的Access查询正在Amount汇总[Actuals_Year]<>[Current_Year],但在您的问题(1)中,您说它应该汇总[Actuals_Year]=[Current_Year]。我的答案遵循Access版本。