0

我想基本上使用 SQL Server 查询计算两年内的百分比差异。

出于某种原因,当我在年份字段上使用 -1 时,它返回 null。

如果我不在今年做-1,我现在所拥有的工作,但显然它返回 100%,因为它是今年与今年的比较,而不是今年与上一年的比较。

这是我的查询:

SELECT Year, 
       Sum(Amount) 
       AS Total, 
       (SELECT Sum(Amount) 
        FROM   Purchases 
        WHERE  Purchases.Year = Budgets.Year) 
       AS Actual, 
       ( ( (SELECT Sum(Amount) 
            FROM   Purchases 
            WHERE  Purchases.Year = Budgets.Year) / Sum(Amount) ) * 100 ) 
       AS 
       BudgetPercentage, 
       ( (SELECT Sum(Amount) 
          FROM   Budgets 
          WHERE  Budgets.Year = Budgets.Year) / (SELECT Sum(Amount) 
                                                 FROM   Budgets 
                                                 WHERE  Budgets.Year = ( 
                                                        Budgets.Year - 1 
                                                                       )) * 100 
       ) AS 
       PerYearPercentage 
FROM   Budgets 
WHERE  ServiceStationId = 1 
GROUP  BY Year 

问题出在 Budgets.Year - 1 上,知道我能做些什么来获得预期的结果吗?

4

1 回答 1

2

对您的查询的快速修复是简单地向PerYearPercentage计算子查询中的表添加不同的别名:

SELECT Year, 
       Sum(Amount) 
       AS Total, 
       (SELECT Sum(Amount) 
        FROM   Purchases 
        WHERE  Purchases.Year = Budgets.Year) 
       AS Actual, 
       ( ( (SELECT Sum(Amount) 
            FROM   Purchases 
            WHERE  Purchases.Year = Budgets.Year) / Sum(Amount) ) * 100 ) 
       AS 
       BudgetPercentage, 
       ( (SELECT Sum(Amount) 
          FROM   Budgets b
          WHERE  b.Year = Budgets.Year) / (SELECT Sum(Amount) 
                                           FROM   Budgets b
                                           WHERE  b.Year = (Budgets.Year - 1)) * 100 
       ) AS 
       PerYearPercentage 
FROM   Budgets 
WHERE  ServiceStationId = 1 
GROUP  BY Year 
于 2012-05-21T13:23:46.623 回答