简体   繁体   中英

SQL Year over year growth percentage from data same query

How do I calculate the percentage difference from 2 different columns, calculated in that same query? Is it even possible?

This is what I have right now:

SELECT 
      Year(OrderDate) AS [Year], 
      Count(OrderID) AS TotalOrders, 
      Sum(Invoice.TotalPrice) AS TotalRevenue
FROM 
    Invoice 
INNER JOIN Order
        ON Invoice.InvoiceID = Order.InvoiceID
GROUP BY Year(OrderDate);

Which produces this table

在此处输入图片说明

Now I'd like to add one more column with the YoY growth, so even when 2016 comes around, the growth should be there..

EDIT: I should clarify that I'd like to have for example next to

2015,5,246.28 -> 346,15942029% ((R2015-R2014) / 2014 * 100)

If you save your existing query as qryBase , you can use it as the data source for another query to get what you want:

SELECT
    q1.Year,
    q1.TotalOrders,
    q1.TotalRevenue,
    IIf
        (
            q0.TotalRevenue Is Null,
            Null,
            ((q1.TotalRevenue - q0.TotalRevenue) / q0.TotalRevenue) * 100
        ) AS YoY_growth
FROM
    qryBase AS q1
    LEFT JOIN qryBase AS q0
    ON q1.Year = (q0.Year + 1);

Access may complain it "can't represent the join expression q1.Year = (q0.Year + 1) in Design View" , but you can still edit the query in SQL View and it will work.

What you are looking for is something like this?

Year    Revenue     Growth
2014    55
2015    246         4.47
2016    350         1.42

You could wrap the original query a twice to get the number from both years.

select orders.year, orders.orders, orders.revenue, 
    (select (orders.revenue/subOrders.revenue)
        from 
        (
        --originalQuery or table link
        ) subOrders
        where subOrders.year = (orders.year-1)
    ) as lastYear
from
(
--originalQuery or table link
) orders

here's a cheap union'd table example.

select orders.year, orders.orders, orders.revenue, 
    (select (orders.revenue/subOrders.revenue)
        from 
        (
        select 2014 as year, 2 as orders, 55.20 as revenue
        union select 2015 as year, 2 as orders, 246.28 as revenue
        union select 2016 as year, 7 as orders, 350.47 as revenue
        ) subOrders
        where subOrders.year = (orders.year-1)
    ) as lastYear
from
(
select 2014 as year, 2 as orders, 55.20 as revenue
union select 2015 as year, 2 as orders, 246.28 as revenue
union select 2016 as year, 7 as orders, 350.47 as revenue
) orders

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM