简体   繁体   中英

Sum SQL Server Count column from Grouped query

I am trying to write a query that takes all content from my database that has been rated higher than 3 stars and returns the top four modules based on star average and highest numbers of ratings. This part works great.

But in order for me to put this into a graph, I need the percentage. So, I need the summary of the count(id_module) column. I have read through a lot of posts and tried to implement a number of solutions but have not been successful - can anyone shed any light for me? I have pasted my query below and the results it brings back - this part works fine... I just need to know how to get the sum of the id module fields - which in this case would be 23... thanks for any help offered!

SELECT TOP 4 
    AVG(rating) AS ratingstars, 
    COUNT(id_module) AS countmodules,  
FROM 
    [db]
WHERE 
    (rating > 3)
GROUP BY 
    id_module 
ORDER BY 
    ratingstars DESC, countmodules DESC
  • ratingstars = 5, 5, 5, 5
  • countstar = 18, 2, 2, 1 (need the sum of these)

In SQL Server 2008+ you can use SUM() OVER() . I'm not sure if this is available in SQL Server 2005.

WITH
CTE
AS
(
    SELECT TOP 4 
        AVG(rating) AS ratingstars, 
        COUNT(id_module) AS countmodules
    FROM [db]
    WHERE (rating > 3)
    GROUP BY id_module 
    ORDER BY ratingstars DESC, countmodules DESC
)
SELECT
    ratingstars
    ,countmodules
    ,SUM(countmodules) OVER () AS SumCountModules
FROM CTE
ORDER BY ratingstars DESC, countmodules DESC
;

maybe this or a sub select:

SELECT ratingstars, SUM(countmodules) as [countmodules] FROM
(
SELECT TOP 4 AVG(rating) AS ratingstars, COUNT(id_module) AS countmodules,FROM   [db],
WHERE 
(rating > 3)
GROUP BY id_module) X
GROUP BY X.ratingstars
ORDER BY X.ratingstars DESC, X.countmodules DESC
SELECT TOP 4 
    AVG(rating) AS ratingstars, 
    COUNT(*) AS countmodules,
    SUM(COUNT(*)) OVER () AS allmodules /* <-- OVER () makes the double aggregate "ok" */
FROM 
    [db]
WHERE 
    rating > 3
GROUP BY 
    id_module 
ORDER BY 
    ratingstars DESC, countmodules DESC

Note this won't limit the sum to just the top four rows as I have realized you may want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM