[英]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.
我希望将最上面的四个名称与最下面的四个名称结合起来,以创建4个名称,同时“总收入”和“口袋”具有值而不是零。
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.
任何帮助是极大的赞赏。
It seems that you don't have to, you can just calculate conditional sum
(with case
): 似乎不必,您可以只计算条件
sum
(使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.