Reputation:
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
Upvotes: 1
Views: 967
Reputation: 17915
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.
Upvotes: 0
Reputation: 32695
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
;
Upvotes: 1
Reputation: 1
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
Upvotes: 0