Windows功能+分区硬

时间:2019-06-07 11:28:43

标签: sql sql-server windows function partition

我需要执行相同的结果,但不需要使用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;

1 个答案:

答案 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 

注意:

  • 如果profitint列,则需要额外的CONVERT
  • 有关SUM函数状态的文档,指出“ .. order_by_clause是必需的...” ,因此像这样使用SUM ... OVER ...更接近书籍:{{ 1}}。