Search code examples
sqlwindow-functions

Problem to fix a question with WindowFunction


For school, I have to answer the following question, using a window function.

For each year, for each month, for each product category, indicate the percentage of that month's turnover that was from the annual turnover of that category.

I tried to use the window function but it didnt work. Because i dont know how to use the over (partition by) function

select 
  catcode, 
  year(besteldatum) as jaar, 
  month(besteldatum) as maand, 
  sum(regelomzet) as omzet, 
  sum(regelomzet) / (
    select sum(regelomzet)
    from ##joinall t2
    where t2.catcode = t1.catcode 
      and year(t2.besteldatum) = year(t1.besteldatum)
    ) * 100 as perc
from ##joinall t1
group by catcode, year(besteldatum), month(besteldatum)
order by catcode, year(besteldatum), month(besteldatum)

Solution

  • With the window functions there's a thing to realize about them.
    They get processed after the GROUP BY.

    Hence, it's possible to sum over a sum.

    And the PARTITION BY in an OVER is kinda similar to GROUP BY.

    SELECT 
      catcode, 
      year(besteldatum) as jaar, 
      month(besteldatum) as maand, 
      sum(regelomzet) as omzet,
    
      cast(
      (sum(regelomzet) /
        SUM(sum(regelomzet)) OVER (PARTITION BY catcode, year(besteldatum))) * 100
       as decimal(5,2)) as perc
    
    FROM bestellingen t
    GROUP BY catcode, year(besteldatum), month(besteldatum)
    ORDER BY 1, 2, 3;