Calculating percentages with GROUP BY query

后端 未结 5 509
太阳男子
太阳男子 2020-12-05 06:28

I have a table with 3 columns which looks like this:

File    User     Rating (1-5)
------------------------------
00001    1        3
00002    1        4
000         


        
相关标签:
5条回答
  • 2020-12-05 07:02
    WITH data AS 
     (SELECT User, Rating, Count(*) AS Count 
      FROM Results
      GROUP BY User, Rating)
    SELECT User, Rating, Count, 
           (0.0+n)/(SUM(Count) OVER (PARTITION BY User))
    FROM data;
    
    0 讨论(0)
  • 2020-12-05 07:05

    In TSQL this should work

    SELECT
        User,
        Rating,
        Count(*), SUM(COUNT(*)) OVER (PARTITION BY User, Rating ORDER BY User, Rating) AS Total,
    Count(*)/(SUM(COUNT(*)) OVER (PARTITION BY User, Rating ORDER BY User, Rating)) AS Percentage
    FROM
        Results
    GROUP BY
        User, Rating
    ORDER BY
        User, Rating
    
    0 讨论(0)
  • 2020-12-05 07:07
    WITH t1 AS 
     (SELECT User, Rating, Count(*) AS n 
      FROM your_table
      GROUP BY User, Rating)
    SELECT User, Rating, n, 
           (0.0+n)/(COUNT(*) OVER (PARTITION BY User)) -- no integer divide!
    FROM t1;
    

    Or

    SELECT User, Rating, Count(*) OVER w_user_rating AS n, 
            (0.0+Count(*) OVER w_user_rating)/(Count(*) OVER (PARTITION BY User)) AS pct
    FROM your_table
    WINDOW w_user_rating AS (PARTITION BY User, Rating);
    

    I would see if one of these or the other yields a better query plan with the appropriate tool for your RDBMS.

    0 讨论(0)
  • 2020-12-05 07:11

    The best way to do this would be with window functions.

    0 讨论(0)
  • 2020-12-05 07:17

    Alternatively, you can do the old-school way — arguably easier to grok:

    select usr.User                   as User   ,
           usr.Rating                 as Rating ,
           usr.N                      as N      ,
           (100.0 * item.N) / total.N as Pct
    from ( select User, Rating , count(*) as N
           from Results
           group by User , Rating
         ) usr
    join ( select User , count(*) as N
           from Results
           group by User
         ) total on total.User = usr.User
    order by usr.User, usr.Rating
    

    Cheers!

    0 讨论(0)
提交回复
热议问题