繁体   English   中英

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

[英]Sum SQL Server Count column from Grouped query

我正在尝试编写一个查询,该查询将从我的数据库中获得评分高于3星的所有内容,并根据星级平均和最高评分数返回前四个模块。 这部分效果很好。

但是为了让我将其放入图表中,我需要百分比。 因此,我需要count(id_module)列的摘要。 我已经阅读了很多文章,并尝试实施许多解决方案,但都没有成功-有人能为我提供启示吗? 我在下面粘贴了查询并将其返回的结果-这部分工作正常...我只需要知道如何获取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
  • 评分星级= 5、5、5、5
  • countstar = 18、2、2、1(需要这些加和)

在SQL Server 2008+中,可以使用SUM() OVER() 我不确定这在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
;

也许这个或一个子选择:

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

请注意,这不会将总和限制为仅前四行,因为我意识到您可能想要这样做。

暂无
暂无

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

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