如何将这两个查询合并为一个查询?

时间:2015-11-19 09:02:44

标签: mysql database

我知道有很多关于此类主题的问题,但我找不到任何有关我的问题的帮助。

我有两个工作查询。我想将它们组合成一个查询。当我尝试将它们组合时,显示的数据不正确。但是,当它们分开时,数据是正确的。

查询1:

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

输出:

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

查询2:

Select Distinct concat(d.FirstName, ' ', d.LastName) as 'Donor',
concat('$', 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;

输出:

+--------------+----------+
| Donor        | Pocket   |
+--------------+----------+
| John Smith   | $1750.00 |
| Linda Smith  | $100.00  |
| Jack Clinton | $200.00  |
| Jane Doe     | $2100.00 |
+--------------+----------+

合并时:

Select Distinct concat(d.FirstName, ' ', d.LastName) as 'Donor', 
concat('$', sum(a.amount)) as 'Total Paid',
concat('$', sum(a2.amount)) as 'Pocket'
From Donor d, Donor d2, Pledge p, Pledge p2, Payment a, Payment a2
where d.donorId=p.donorId
and p.pledgeId = a.pledgeId
and (a2.CompanyId is null)
and d2.DonorId = p2.DonorId
and p2.pledgeId = a2.PledgeId
group by d.DonorId;

输出:

+--------------+------------+-----------+
| Donor        | Total Paid | Pocket    |
+--------------+------------+-----------+
| John Smith   | $24500.00  | $20750.00 |
| Linda Smith  | $1750.00   | $12450.00 |
| Jack Clinton | $1400.00   | $8300.00  |
| Jane Doe     | $14700.00  | $8300.00  |
+--------------+------------+-----------+

这些查询中的每一个都有一个供体名称列和一个带有一些货币值的列。在我的最终查询中,我想要一个包含捐赠者名称的列,一个标记为“Total Paid”的列和一个标记为“Pocket”的列。当我将这两个查询组合在一起时,“总付费”列将全部搞砸,以及“口袋”列。

我知道如果没有表格架构,这可能很难帮助,但我想我会试一试。提前谢谢。

1 个答案:

答案 0 :(得分:0)

试试这个:

select
    'Donor',concat('$',sum('Total Paid')) as 'Total Paid',concat('$',sum('Pocket')) as 'Pocket'
from(
        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
    ) group by Donor;

注意:如果您使用的是MySQL数据库,则应使用backticks(“`”)而不是列名的单引号。