How do I count the number of records returned by a group by query,
For eg:
select count(*)
from temptable
group by column_1, column_2, column_3, co
I was trying to achieve the same without subquery and was able to get the required result as below
SELECT DISTINCT COUNT(*) OVER () AS TotalRecords
FROM temptable
GROUP BY column_1, column_2, column_3, column_4
A CTE worked for me:
with cte as (
select 1 col1
from temptable
group by column_1
)
select COUNT(col1)
from cte;
You could do:
select sum(counts) total_records from (
select count(*) as counts
from temptable
group by column_1, column_2, column_3, column_4
) as tmp
select *
, concat(cast(cast((ThirdTable.Total_Records_in_Group * 100 / ThirdTable.Total_Records_in_baseTable) as DECIMAL(5,2)) as varchar), '%') PERCENTage
from
(
SELECT FirstTable.FirstField, FirstTable.SecondField, SecondTable.Total_Records_in_baseTable, count(*) Total_Records_in_Group
FROM BaseTable FirstTable
JOIN (
SELECT FK1, count(*) AS Total_Records_in_baseTable
FROM BaseTable
GROUP BY FK1
) SecondTable
ON FirstTable.FirstField = SecondTable.FK1
GROUP BY FirstTable.FirstField, FirstTable.SecondField, SecondTable.Total_Records_in_baseTable
ORDER BY FirstTable.FirstField, FirstTable.SecondField
) ThirdTable
The simplest solution is to use a derived table:
Select Count(*)
From (
Select ...
From TempTable
Group By column_1, column_2, column_3, column_4
) As Z
Another solution is to use a Count Distinct:
Select ...
, ( Select Count( Distinct column_1, column_2, column_3, column_4 )
From TempTable ) As CountOfItems
From TempTable
Group By column_1, column_2, column_3, column_4
How about using a COUNT OVER (PARTITION BY {column to group by}) partitioning function in SQL Server?
For example, if you want to group product sales by ItemID and you want a count of each distinct ItemID, simply use:
SELECT
{columns you want} ,
COUNT(ItemID) OVER (PARTITION BY ItemID) as BandedItemCount ,
{more columns you want}... ,
FROM {MyTable}
If you use this approach, you can leave the GROUP BY out of the picture -- assuming you want to return the entire list (as you might do report banding where you need to know the entire count of items you are going to band without having to display the entire set of data, i.e. Reporting Services).