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

Agregate in mssql server

I need help to create new columns to calculate total of each employee salary and bonus

id          Name        PaymentType   Payment   
----        -----       ------        -------
1           John         Salary       100
2           Peter        Salary       100
3           John         Bonus        20
4           Russel       Salary       100
5           Bill         Salary       100
6           Bill         Bonus        40
7           John         Salary       100

How can I make something like below

Name          Salary     Bonus
John          200        20
Peter         100        0
Russel        100        0
Bill          100        40
 

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

>Solution :

We can use conditional aggregation here:

SELECT
    Name,
    SUM(CASE WHEN PaymentType = 'Salary' THEN Payment ELSE 0 END) AS Salary,
    SUM(CASE WHEN PaymentType = 'Bonus'  THEN Payment ELSE 0 END) AS Bonus
FROM yourTable
GROUP BY Name;
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