cancel
Showing results for 
Search instead for 
Did you mean: 
Data Engineering
Join discussions on data engineering best practices, architectures, and optimization strategies within the Databricks Community. Exchange insights and solutions with fellow data engineers.
cancel
Showing results for 
Search instead for 
Did you mean: 

PIVOT on month and quarter

ossinova
Contributor II

I want to simplify this query:

SELECT 
year(EntryDate) Year,
AccountNumber,
sum(CreditBase - DebitBase) FILTER(WHERE month(EntryDate) = 1) AS jan_total,
sum(CreditBase - DebitBase) FILTER(WHERE month(EntryDate) = 2) AS feb_total,
sum(CreditBase - DebitBase) FILTER(WHERE month(EntryDate) = 3) AS mar_total,
sum(CreditBase - DebitBase) FILTER(WHERE month(EntryDate) = 4) AS apr_total,
sum(CreditBase - DebitBase) FILTER(WHERE month(EntryDate) = 5) AS may_total,
sum(CreditBase - DebitBase) FILTER(WHERE month(EntryDate) = 6) AS jun_total,
sum(CreditBase - DebitBase) FILTER(WHERE month(EntryDate) = 7) AS jul_total,
sum(CreditBase - DebitBase) FILTER(WHERE month(EntryDate) = 😎 AS aug_total,
sum(CreditBase - DebitBase) FILTER(WHERE month(EntryDate) = 9) AS sep_total,
sum(CreditBase - DebitBase) FILTER(WHERE month(EntryDate) = 10) AS oct_total,
sum(CreditBase - DebitBase) FILTER(WHERE month(EntryDate) = 11) AS nov_total,
sum(CreditBase - DebitBase) FILTER(WHERE month(EntryDate) = 12) AS dec_total,
sum(CreditBase - DebitBase) FILTER(WHERE quarter(EntryDate) = 1) AS q1_total,
sum(CreditBase - DebitBase) FILTER(WHERE quarter(EntryDate) = 2) AS q2_total,
sum(CreditBase - DebitBase) FILTER(WHERE quarter(EntryDate) = 3) AS q3_total,
sum(CreditBase - DebitBase) FILTER(WHERE quarter(EntryDate) = 4) AS q4_total
FROM prod.gold.finance_financeentry
WHERE EntryDate BETWEEN "2022-01-01" AND "2023-02-28"
GROUP BY year, AccountNumber
ORDER BY Year, AccountNumber;

Into something like this:

SELECT * FROM (
  SELECT  year(EntryDate) year, month(EntryDate) month, quarter(EntryDate) quarter, AccountNumber, CreditBase, DebitBase
  FROM prod.gold.finance_financeentry
  WHERE EntryDate BETWEEN DATE '2022-01-01' AND DATE '2023-02-28'
)
PIVOT (SUM(CreditBase - DebitBase) AS BalanceInBase
  FOR month
  IN (1 JAN, 2 FEB, 3 MAR, 4 APR, 5 MAY, 6 JUN,
      7 JUL, 8 AUG, 9 SEP, 10 OCT, 11 NOV, 12 DEC)
  FOR quarter
  IN (1 Q1, 2 Q2, 3 Q3, 4 Q4)
  )

Is this possible somehow?

1 REPLY 1

Lakshay
Esteemed Contributor

Hi @Oscar Dyremyhr​ , PIVOT doesn't support two FOR clauses. You can PIVOT either on month or on quarter.

https://docs.databricks.com/sql/language-manual/sql-ref-syntax-qry-select-pivot.html

Connect with Databricks Users in Your Area

Join a Regional User Group to connect with local Databricks users. Events will be happening in your city, and you won’t want to miss the chance to attend and share knowledge.

If there isn’t a group near you, start one and help create a community that brings people together.

Request a New Group