每种类型的客户的销售百分比

问题描述 投票:0回答:1

我想找到每种客户类型每周的销售百分比。我可以看到数学运算,但无法弄清楚如何编写查询。

SELECT 
    c.customerType as 'Customer Type', 
    DATEPART(WEEK, o.orderDate) as 'Week of the year', 
    COUNT(c.customerType)  as 'Number of sales' 
from [dbo].[Order] o
    JOIN Customer c ON c.id = o.customerId
GROUP BY c.customerType, DATEPART(WEEK, o.orderDate)

此查询输出按客户类型分组的每个销售的计数。

CustomerType  Week   Number of Sales
Cash          36      248
Corporate     36      10
Personal      36      5
Cash          37      113
Corporate     37      3
Personal      37      2
Cash          38      136
Corporate     38      7
Personal      38      2
Cash          39      138
Corporate     39      4
Personal      39      3
sql-server ssms percentage
1个回答
0
投票

您可以包装查询并使用窗口函数:

select 
    t.*,
    (1.0 * [Number of sales])
        /(sum([Number of sales]) over(partition by [Customer Type]) 
        * 100
        [Percent of Total Sales]
from (
    select 
        c.customerType as [Customer Type], 
        datepart(week, o.orderDate) as [Week of the year], 
        count(c.customerType) as [Number of sales],     
    from [dbo].[Order] o
    join Customer c ON c.id = o.customerId
    group by c.customerType, datepart(week, o.orderDate)
) t
© www.soinside.com 2019 - 2024. All rights reserved.