windows 功能+硬盘分区
windows function + partition hard
我需要做同样的结果,但不是用连接而是 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;
没有示例数据很难,但是如果您想使用不带 CROSS JOIN
并使用 window 函数的语句,下一条语句可能会有所帮助:
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 函数的文档指出," .. order_by_clause 是必需的...",所以像这样使用
SUM ... OVER ...
更接近书籍:SUM(profit) OVER (PARTITION BY [year] ORDER BY (SELECT NULL))
.
我需要做同样的结果,但不是用连接而是 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;
没有示例数据很难,但是如果您想使用不带 CROSS JOIN
并使用 window 函数的语句,下一条语句可能会有所帮助:
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 函数的文档指出," .. order_by_clause 是必需的...",所以像这样使用
SUM ... OVER ...
更接近书籍:SUM(profit) OVER (PARTITION BY [year] ORDER BY (SELECT NULL))
.