Osoba Osaze
Osoba Osaze

Reputation: 93

Get quarter on quarter growth with SQL for current quarter

I'm trying to get the quarter on quarter revenue growth for only the current quarter from a dataset. I currently have a query that looks something like this

Select
  x.Year,
  x.quarter,
  x.product,
  x.company_id,
  y.company,
  SUM(x.revenue)
FROM 
  company_directory y
  LEFT JOIN (
SELECT
  DATEPART(YEAR, @date) year,
  DATEPART(QUARTER, @date) quarter,
  product,
  SUM(revenue)
FROM sales
WHERE year => 2018 ) x
ON y.company_id = x.company_id

The data I get is in this format

Year  Quarter  Product  company_id  company    revenue
2020  Q2       Banana   1092        companyX   $100

What I'm trying to do is get quarter on quarter growth for revenue if it's reporting the current quarter. So for example, in the above data, because we're in Q2-2020, I want an extra column to say QoQ is x% which will compare Q2 vs Q1 revenue. If the row is reporting Q1-2020 or Q2-2019 QoQ will be empty because neither of those are the current quarter based on today's date.

Expected result

Year  Quarter  Product  company_id  company    revenue  QoQ
2020  Q2       Banana   1092        companyX   $100     20%
2020  Q1       Pear     1002        companyX   $23      NULL

I'm not entirely sure how to go about this, haven't had much luck searching. Any idea how I can implement?

Upvotes: 0

Views: 1859

Answers (2)

GMB
GMB

Reputation: 222502

You can use window functions.

select
    s.yr,
    s.qt,
    s.product,
    s.company_id,
    cd.company,
    s.revenue,
    1.0 * (
        s.revenue 
        - lag(s.revenue) over(partition by s.product, s.company_id order by s.yr, s.qt)
    ) / lag(s.revenue) over(partition by s.product, s.company_id order by s.yr, s.qt) as QoQ
from company_directory cd
inner join (
    select
        datepart(year, sales_date) yr,
        datepart(quarter, sales_date) qt,
        product,
        company_id,
        sum(revenue) revenue
    from sales
    where sales_date >= '2018-01-01'
    group by 
        datepart(year, sales_date) year,
        datepart(quarter, sales_date) quarter,
        product,
        company_id
)  s on s.company_id = cd.company_id

Notes:

  • your code is not valid MySQL; I assume that you are running SQL Server instead of MySQL

  • the use of a variable in the subquery does not make sense - I assume that you have a column called sales_date in table sales that holds the sales date

  • your group by clauses are inconsistent with your select clauses - I assume that you want the quarter to quarter sales growth per company and per product

  • you might need to ajust the QoQ computation to your actual definition of the quarter to quarter growth

  • I don't see the point for a left join, so I used inner join instead

Upvotes: 1

Nawaf
Nawaf

Reputation: 540

You need analytical window function LAG

https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=40a7ba897df766f913ebd99e2f2a0f4e

Upvotes: 0

Related Questions