how to calculate percent of total within group by statement?

前端 未结 4 1907
野的像风
野的像风 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 04:58

    Use a nested query to get the daily total:

    BEGIN
    
        create table #sales (name varchar(10), salesdate date )
    
        insert into #sales (name, salesdate) values 
            ('joe', '01-01-2013'), 
            ('joe', '01-01-2013'), 
            ('joe', '01-01-2013'), 
            ('dave', '01-01-2013'),  
            ('joe', '01-02-2013'),
            ('dave', '01-02-2013')
    
        SELECT name, salesdate, COUNT(*) AS personDailyTotal, MAX(dailyTotal) AS dailyTotal, 
            (COUNT(*) * 100.0) / MAX(dailyTotal) AS [Percent]
        FROM #sales
        INNER JOIN (
            SELECT salesdate as [day], COUNT(*) as dailyTotal 
            FROM #sales 
            GROUP BY salesdate
        ) AS [Total] ON salesdate = [day]
        GROUP BY name, salesdate
    
    END
    

提交回复
热议问题