分组TSQL查询中的总计数

时间:2012-07-27 11:43:17

标签: sql sql-server-2008 tsql group-by

我有一个性能繁重的查询,根据其他表中的数据等过滤掉许多不需要的记录。

我正在对一列进行平均,并且还返回每个平均组的计数。这一切都很好。

但是,我还要包括TOTAL计数的百分比。

有没有办法在不重新运行整个查询或显着增加性能负载的情况下获得此总计数?

我还希望如果我不需要完全重构子查询(例如通过获取其外部的总计数),但可以在必要时进行。

SELECT 
    data.EquipmentId,
    AVG(MeasureValue) AS AverageValue,
    COUNT(data.*) AS BinCount
    COUNT(data.*)/ ???TotalCount??? AS BinCountPercentage
FROM
(SELECT * FROM MultipleTablesWithJoins) data
GROUP BY data.EquipmentId

2 个答案:

答案 0 :(得分:7)

请参阅Window functions

SELECT 
    data.EquipmentId,
    AVG(MeasureValue) AS AverageValue,
    COUNT(*) AS BinCount,
    COUNT(*)/ cast (cnt as float) AS BinCountPercentage
FROM
(SELECT *,
      -- Here is total count of records
        count(*) over() cnt
 FROM MultipleTablesWithJoins) data
GROUP BY data.EquipmentId, cnt

编辑:忘了实际划分数字。

答案 1 :(得分:1)

另一种方法:

with data as
(
    SELECT * FROM MultipleTablesWithJoins
)
,grand as
(
    select count(*) as cnt from data
)
SELECT 
    data.EquipmentId,
    AVG(MeasureValue) AS AverageValue,
    COUNT(data.*) AS BinCount
    COUNT(data.*)/ grand.cnt AS BinCountPercentage
FROM data cross join grand
GROUP BY data.EquipmentId