Mysql连接查询?

时间:2016-05-03 10:09:24

标签: mysql

ToBeCollected

Id     Name          Amount
1      MR XXX         10000  
2      Mr YYY         15000
3      Mr ZZZ         12000

收集

ID    Name        Amount
1     Mr XXX       5000
2     Mr XXX       2000
3     Mr YYY      12000
4     Mr YYY       1000

我正在寻找的是这个。

ID    Name   ToBeCollected    Collected     Balance
1    Mr XXX     10,000           7,000       3,000
2    Mr YYY     15,000          13,000       2,000
3    Mr ZZZ     12,000               0      12,000

4 个答案:

答案 0 :(得分:1)

尝试此查询....

SELECT t.id,t.name,max(t.amt) as tobeCol,
       coalesce(s.amt,0) as Col,
       max(t.amt) - coalesce(s.amt,0) as Balance
FROM ToBeCollected t
LEFT JOIN (select sum(amt) as amt,name from Collected group by name) s on s.name=t.name
group by t.name,t.id;

答案 1 :(得分:0)

您可以使用简单的join, max(), GROUP BYIFNULL()函数

来实现此输出

所以你的查询将是,

SELECT ToBeCollected.Id,ToBeCollected.Name,
       max(ToBeCollected.Amount) as ToBeCollected,
       IFNULL(sum(Collected.Amount),0) as Collected,
       max(ToBeCollected.Amount) - IFNULL(sum(Collected.Amount),0) as Balance
   FROM ToBeCollected
   LEFT JOIN Collected ON Collected.Name = ToBeCollected.Name
   GROUP BY ToBeCollected.Id

注意:需要输出,您可以查看SQLFiddle,然后可以参考此Document

答案 2 :(得分:0)

根据您的示例,这两个表按名称列链接。 你可以试试这个:

SELECT tb.Id, tb.Name, tb.Amount ToBeCollected,
ifnull(SUM(cl.Amount), 0) Collected,
(tb.Amount - ifnull(SUM(cl.Amount), 0)) Balance
FROM ToBeCollected tb LEFT JOIN Collected cl ON (tb.Name = cl.Name)
GROUP BY tb.Name

答案 3 :(得分:0)

select 
t.ID,
t.name,
t.Amount as ToBeCollected,
if(c.total_amount_collected is null, 0, c.total_amount_collected) as Collected,
if(c.total_amount_collected is null, t.amount, t.amount - c.total_amount_collected)  as Balance
from ToBeCollected t
left join (select Name, sum(Amount) as total_amount_collected from Collected group by Name) as c
on(t.Name = c.Name)

子选择用于计算收集的数量,因为table_Collected中每个名称有多行。 ifs用于补偿t中没有相应行的行(易于遵循)