Find customers whose yearly total spending is strictly increasing

  Kiến thức lập trình

How to I remove the duplicate customer_id row. For Example for customer_id = 8 I have two entries with NULL, how do I combine the two entries and remove the NULL value from it

WITH customer_yearly_spending AS ( SELECT customer_id, EXTRACT(YEAR FROM invoice_date) AS transaction_year, SUM(total) AS year_spending FROM invoice WHERE EXTRACT(YEAR FROM invoice_date) < 2025 GROUP BY customer_id, EXTRACT(YEAR FROM invoice_date) ), yearly_spending_change AS ( SELECT customer_id, transaction_year, year_spending, LAG(year_spending) OVER (PARTITION BY customer_id ORDER BY transaction_year) AS previous_year_spending, LEAD(year_spending) OVER (PARTITION BY customer_id ORDER BY transaction_year) AS next_year_spending FROM customer_yearly_spending ) SELECT DISTINCT customer_id, previous_year_spending, next_year_spending FROM yearly_spending_change;

I am unable to figure out the mistake in the query which is resulting in multiple row for same customer_id

New contributor

Aditya Mishra is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT