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

Select multiple rows into a single one using SELECT CASE

I’m trying to select this results of multiple rows into a single row and grouping/merging them by DocNumber.

I have a table like this

create table PaymentsTable (
    PaymentId varchar(10),
    DocNumber varchar(20),
    DocType varchar(40),
    Amount decimal(18,2)
);

insert into paymentstable values (01,2020, 'receipt', 100);
insert into paymentstable values (02,2020, 'receipt',150);
insert into paymentstable values (03,2020, 'receipt',10);
insert into paymentstable values (01,600, 'order', 1500);
insert into paymentstable values (01,220, 'invoice', 650);
insert into paymentstable values (02,220, 'invoice',500);

The table looks like this

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

PaymentId DocNumber DocType Amount
01 2020 Receipt 100
02 2020 Receipt 150
03 2020 Receipt 10
01 600 Order 1500
01 220 Invoice 650
02 220 Invoice 500

I’m trying something like this

SELECT P.docnumber
    , p.doctype
    , CASE WHEN P.Paymentid = 01 THEN p.Amount END AS 'Cash'
    , CASE WHEN P.Paymentid = 02 THEN p.Amount END AS 'Debit'
    , CASE WHEN P.Paymentid = 03 THEN p.Amount END AS 'Credit'
FROM PaymentsTable AS P

My Result:

enter image description here

Desired:

Desired

>Solution :

Seems you just need GROUP BY and SUM?

SELECT P.docnumber
    , p.doctype
    , SUM(CASE WHEN P.Paymentid = 01 THEN p.Amount END) AS 'Cash'
    , SUM(CASE WHEN P.Paymentid = 02 THEN p.Amount END) AS 'Debit'
    , SUM(CASE WHEN P.Paymentid = 03 THEN p.Amount END) AS 'Credit'
FROM PaymentsTable AS P
GROUP BY P.docnumber, p.doctype
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