how to calculate percent of total within group by statement?

前端 未结 4 1929
野的像风
野的像风 2021-01-13 04:19

I have a table with 1 record per sale per salesperson per day

NAME  DATE
joe   1-1-13
joe   1-1-13
joe   1-1-13
dave  1-1-13
joe   1-2-13

I

4条回答
  •  自闭症患者
    2021-01-13 05:04

    Not the most elegant way to do it, but you can try this -

    select [name],[salesdate], COUNT(*) as dayTotal, 
    SUM(COUNT(*)) over() as AllSales, 
    (COUNT(*) * 1.0) / SUM(COUNT(*)) over() as dayPercent
    FROM [dbo].[sales]
    group by [name], [salesdate]
    

    I removed the # in your table name. Btw, this code depends on OVER() clause. You can find out how to truncate the excess zeros yourself.

    name    salesdate   dayTotal    AllSales    dayPercent
    dave    2013-01-01  1           5           0.200000000000
    joe   2013-01-01    3           5           0.600000000000
    joe   2013-01-02    1           5           0.200000000000
    

    HTH.

    If that query looks too complicated to you, then look at this one first. It will give you an idea of what I am trying to do.

    select [name],[salesdate], COUNT(*) as dayTotal, 
    SUM(COUNT(*)) over() as AllSales
    FROM [dbo].[sales]
    group by [name], [salesdate]
    

提交回复
热议问题