我正在尝试编写查询,为每个客户计算其当年总利润的一部分。
我通过使用join来编写此查询,但是我想通过Windows函数+分区来编写此查询。
SELECT t1.Customer_ID, t1.Year, [Sum of Profit]/[Total Profit] [Part of Profit]
FROM
(SELECT Customer_ID, DATEPART(YEAR, Order_Date) Year,
SUM(Try_convert(float,Profit)) [Sum of Profit]
FROM Orders
GROUP BY Customer_ID, DATEPART(YEAR, Order_Date)) t1
JOIN
(SELECT DATEPART(YEAR, Order_Date) Year, SUM(Try_convert(float,Profit)) [Total Profit]
FROM Orders
GROUP BY DATEPART(YEAR, Order_Date)) t2
ON t1.Year = t2.Year
如何使用Windows函数+分区进行相同的查询?
答案 0 :(得分:0)
您可以在聚合查询中使用窗口函数:
SELECT Customer_ID, YEAR(Order_Date) as Year,
SUM(Try_convert(float, Profit)) as [Sum of Profit],
(SUM(Try_convert(float, Profit)) /
SUM(SUM(Try_convert(float, Profit))) OVER ()
) as ratio
FROM Orders
GROUP BY Customer_ID, YEAR(Order_Date)