[英]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
在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.