SQL with Group By and SUM

Kmcnet 1,066 Reputation points
2023-10-08T01:03:32.78+00:00

Hello everyone and thanks for the help in advance. I have a SQL statement

		Select Distinct PatientRace,  Count(*) as Count from tblPtMstr1 Where PatientID In 			(Select Distinct MRNumber from tblPatientVisits Where (CheckedOut Between @BeginningDate and @EndingDate)) 			Group By PatientRace Order By Count Desc

I want to create a total row as the last row entry, but can't figure out how to do this, either by SUM or Roll Up. Any help would be appreciated.

SQL Server Other
0 comments No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2023-10-08T09:59:49.6666667+00:00

    Change

    Group By PatientRace
    

    to

    Group By GROUPING SETS ((PatientRace), ())
    

    To get that row last in the result set, you need to change the ORDER BY clause to

    ORDER BY grouping(PatientRace), "Count"
    

    By the way, remove the DISTINCT from the SELECT list. It makes no sense when you already have GROUP BY.


1 additional answer

Sort by: Most helpful
  1. Anonymous
    2023-10-09T02:09:34.25+00:00

    Hi @Kmcnet

    As a supplement, you can learn more about 'GROUPING SETS'.

    https://www.sqlservertutorial.net/sql-server-basics/sql-server-grouping-sets/

    If you can provide some test data, it will help us better help you solve the problem.

    Best regards,

    Percy Tang


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.