Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Total Count in Grouped TSQL Query

I have an performance heavy query, that filters out many unwanted records based on data in other tables etc.

I am averaging a column, and also returning the count for each average group. This is all working fine.

However, I would also like to include the percentage of the TOTAL count.

Is there any way of getting this total count without rerunning the whole query, or increasing the performance load significantly?

I would also prefer if I didn't need to completely restructure the sub query (e.g. by getting the total count outside of it), but can do if necessary.

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
like image 644
Paul Grimshaw Avatar asked Feb 20 '23 17:02

Paul Grimshaw


1 Answers

See 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

EDIT: forgot to actually divide the numbers.

like image 137
Nikola Markovinović Avatar answered Mar 05 '23 20:03

Nikola Markovinović