简体   繁体   English

来自分组查询的SQL Server计数列总和

[英]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. 我正在尝试编写一个查询,该查询将从我的数据库中获得评分高于3星的所有内容,并根据星级平均和最高评分数返回前四个模块。 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. 因此,我需要count(id_module)列的摘要。 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! 我在下面粘贴了查询并将其返回的结果-这部分工作正常...我只需要知道如何获取id模块字段的总和-在这种情况下为23 ...感谢您的帮助提供!

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 评分星级= 5、5、5、5
  • countstar = 18, 2, 2, 1 (need the sum of these) countstar = 18、2、2、1(需要这些加和)

In SQL Server 2008+ you can use SUM() OVER() . 在SQL Server 2008+中,可以使用SUM() OVER() I'm not sure if this is available in SQL Server 2005. 我不确定这在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. 请注意,这不会将总和限制为仅前四行,因为我意识到您可能想要这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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