ethanm1
ethanm1

Reputation: 15

How do I combine these two queries using Union?

I have two queries that I am trying to combine into one using a union statement.

This is what I have so far:

    (Select Distinct concat(d.FirstName, ' ', d.LastName) as 'Donor',
        sum(a.amount) as 'Total Paid', 0 as Pocket 
        From Donor d, Pledge p, Payment a
        Where d.DonorId=p.DonorId
        and p.pledgeId = a.pledgeId
        group by d.donorid)

        union all

    (Select Distinct concat(d.FirstName, ' ', d.LastName) as 'Donor',
        0 as 'Total Paid',sum(a.amount) as 'Pocket'
        From Donor d, Pledge p, Payment a
        Where (a.CompanyId is null) 
        and d.DonorId=p.DonorId
        and p.pledgeId = a.pledgeId
        group by d.donorid);

This creates:

+--------------+------------+---------+
| Donor        | Total Paid | Pocket  |
+--------------+------------+---------+
| John Smith   |    3500.00 |    0.00 |
| Linda Smith  |     250.00 |    0.00 |
| Jack Clinton |     200.00 |    0.00 |
| Jane Doe     |    2100.00 |    0.00 |
| John Smith   |       0.00 | 1750.00 |
| Linda Smith  |       0.00 |  100.00 |
| Jack Clinton |       0.00 |  200.00 |
| Jane Doe     |       0.00 | 2100.00 |
+--------------+------------+---------+

I don't know how to get rid of the repeating sections. I want the top four names to be combined with the bottom four names to create 4 names with both "total paid" and "pocket" to have values and not zeros.

Just to be clear, I want the output to look like this:

+--------------+------------+---------+
| Donor        | Total Paid | Pocket  |
+--------------+------------+---------+
| John Smith   |    3500.00 | 1750.00 |
| Linda Smith  |     250.00 |  100.00 |
| Jack Clinton |     200.00 |  200.00 |
| Jane Doe     |    2100.00 | 2100.00 |
+--------------+------------+---------+ 

I know I am missing something about the union statement, I just don't know what it is. Any help is greatly appreciated.

Upvotes: 1

Views: 41

Answers (1)

potashin
potashin

Reputation: 44581

It seems that you don't have to, you can just calculate conditional sum (with case):

select concat(d.FirstName, ' ', d.LastName) as 'Donor'
     , sum(a.amount) as 'Total Paid'
     , sum(case when a.CompanyId is null then a.amount else 0 end) as 'Pocket' 
from Donor d
join Pledge p on d.DonorId = p.DonorId
join Payment a on p.pledgeId = a.pledgeId
group by d.donorid

Upvotes: 2

Related Questions