Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to calculate the sum of a column by individual category separately?

I need some help

I need to calculate the total hours of each employee and also show all the dates of each employee in a same table.

My Table is like below-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Employee Date hours
Rohit 06-03-2022 9
Rohit 07-03-2022 8
Rohit 08-03-2022 9
Rohit 09-03-2022 9
Rohit 10-03-2022 10
Rohit 11-03-2022 8
Rohit 12-03-2022 8
Rohit 06-03-2022 7
Raj 07-03-2022 8
Raj 08-03-2022 4
Raj 09-03-2022 3
Raj 10-03-2022 5
Raj 11-03-2022 8
Raj 12-03-2022 8

The output should be like this

Employee Date hours
Rohit 06-03-2022 9
Rohit 07-03-2022 8
Rohit 08-03-2022 9
Rohit 09-03-2022 9
Rohit 10-03-2022 10
Rohit 11-03-2022 8
Rohit 12-03-2022 8
Rohit 06-03-2022 7
Total 68
Raj 07-03-2022 8
Raj 08-03-2022 4
Raj 09-03-2022 3
Raj 10-03-2022 5
Raj 11-03-2022 8
Raj 12-03-2022 8
Total 36

>Solution :

You can use GROUPING SETS for this

SELECT
  Employee = CASE WHEN GROUPING(t.Date) = 0 THEN t.Employee ELSE 'Total' END,
  t.Date,
  hours = SUM(t.hours)
FROM YourTable t
GROUP BY GROUPING SETS (
    (Employee, Date),
    (Employee)
);

db<>fiddle

The GROUPING() function tells you whether a column has been aggregated for that row

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading