我需要执行相同的结果,但不需要使用join,而是使用Windows函数+分区。 输出是年份,客户ID和客户权益与一年中所有利润的比率。
year Customer_ID ratio
2012 2 0.0222
2012 4 0.049
2012 37 0.015
2013 2 0.124
this is the join that work
SELECT a.year, a.Customer_ID, a.profit/b.profit as ratio
FROM ( select year(order_date) as year, Customer_ID, sum(Profit) as profit
from [targil 2].[dbo].[exc2 - orders]
group by year(order_date) , Customer_ID
) A
CROSS JOIN (select year(order_date) as year, sum(Profit) as profit
from [targil 2].[dbo].[exc2 - orders]
group by year(order_date)) B
where a.year = b.year;
答案 0 :(得分:0)
没有示例数据很难,但是如果您要使用没有CROSS JOIN
的语句并使用窗口函数,那么下一条语句可能会有所帮助:
SELECT
a.[year],
a.Customer_ID,
a.profit / SUM(a.profit) OVER (PARTITION BY a.[year]) as ratio
FROM (
SELECT
YEAR(order_date) as [year],
Customer_ID,
SUM(Profit) as profit
FROM [targil 2].[dbo].[exc2 - orders]
GROUP BY YEAR(order_date), Customer_ID
) a
注意:
profit
是int
列,则需要额外的CONVERT
。 SUM ... OVER ...
更接近书籍:{{ 1}}。