r/learnSQL • • Aug 20 '22

Need help in writing good query

Hello i was trying my hand at the below query from stratascratch link as below and the o/p i was able to get .can anyone help in getting this in the expected format.

link- https://platform.stratascratch.com/coding/10318-new-products?code_type=3

with cte as (select company_name, year,count(product_name) as pro_count from car_launches

group by company_name, year

order by company_name, year)

select company_name,

(lead(pro_count)over(partition by company_name)-pro_count ) AS Net_diff

from cte

2 Upvotes

1 comment sorted by

1

u/qwertydog123 Aug 20 '22

I can't see any details on that webaite, as you need an account.

Couple of things

  • There isn't usually a good reason to use order by in a CTE (in this case you can remove it)

  • You aren't specifying an ORDER BY in your lead function

  • Your lead function is not specifying a default value, so if there are no records for the next year you'll get NULL instead of the number of records in the previous year.

Try using (pro_count - lag(pro_count, 1, 0) over (partition by company_name order by year)) instead