Armand
Armand

Reputation: 10264

Get percentage over two years in SQL Server query

I want to basically calculate the percentage difference over two years using a SQL Server query.

For some reason when I use -1 on the year field it returns null.

What I have at the moment works if I don't do the -1 on the year, but obviously it returns 100% because it is comparing this year with this year and not this year with the previous year.

Here is my query:

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 

The problem is with the Budgets.Year - 1, any idea what I can do to get the desired result?

Upvotes: 0

Views: 868

Answers (1)

Andriy M
Andriy M

Reputation: 77717

A quick fix to your query would be simply to add different aliases to the the tables in the subqueries where PerYearPercentage is calculated:

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 

Upvotes: 2

Related Questions