对于学校,我必须使用窗口功能来回答以下问题。
对于每个产品类别,在每年,每个月中,指出该类别的年营业额中该月营业额的百分比。
我尝试使用窗口功能,但是没有用。因为我不知道如何使用over(partition by)函数
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)
答案 0 :(得分:1)
有了window functions,关于它们的事情应该有所认识。
它们在GROUP BY之后得到处理。
因此,可以求和。
OVER中的PARTITION BY类似于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;