0

我想对来自不同表 acc 的两个字段求和labour_master_id。但是当我得到结果时,它显示出不同的结果。

这是我尝试过的

select  labours.labour_master_id, 
    sum(labours.amount_paid), 
    sum(labour_cashcredits.amount_paid) 
FROM labours 
left join labour_cashcredits 
    on labours.labour_master_id=labour_cashcredits.labour_master_id 
group by labours.labour_master_id

它可能映射两次,因此显示错误的结果。

现在总和出现问题。

知道怎么做吗?

我在这个查询中有错误..请帮助

select  l.labour_master_id, l.amount_paid as payable, cc.amount_paid as paid
                FROM
                (
                  select labour_master_id, sum(amount_paid) amount_paid
                  from labours 
                  group by labour_master_id
                ) l
                left join
                (
                  select labour_master_id, sum(amount_paid) amount_paid
                  from labour_cashcredits 
                  group by labour_master_id
                ) cc
                                left join
                (
                  select name,id
                  from labour_masters
                ) lm
                    on l.labour_master_id=cc.labour_master_id 
on l.labour_master_id=lm.labour_masters.id
4

4 回答 4

1

您可以尝试使用子查询在每个表中执行求和:

select  l.labour_master_id, 
    l.amount_paid, 
    cc.amount_paid
FROM
(
  select labour_master_id, sum(amount_paid) amount_paid
  from labours 
  group by labour_master_id
) l
left join
(
  select labour_master_id, sum(amount_paid) amount_paid
  from labour_cashcredits 
  group by labour_master_id
) cc
    on l.labour_master_id=cc.labour_master_id 
于 2012-12-19T11:42:34.183 回答
0

用这个 -

      SELECT   labours.labour_master_id, SUM (labours.amount_paid),
     SUM (labour_cashcredits.amount_paid)
  FROM labours,labour_cashcredits
     where labours.labour_master_id = labour_cashcredits.labour_master_id
 GROUP BY labours.labour_master_id
于 2012-12-19T11:39:29.887 回答
0

希望这是你想要的

select  labours.labour_master_id, 
    sum(ifnull(labours.amount_paid,0))+
    sum(ifnull(labour_cashcredits.amount_paid),0) sum
FROM labours 
left join labour_cashcredits 
    on labours.labour_master_id=labour_cashcredits.labour_master_id 
group by labours.labour_master_id
于 2012-12-19T11:42:50.347 回答
0

尝试对第二个 SUM 使用子查询:

SELECT  labours.labour_master_id, SUM(labours.amount_paid), 
          ( SELECT SUM(amount_paid) FROM labour_cashcredits 
            WHERE labour_master_id = labours.labour_master_id 
            GROUP BY labour_master_id
           ) AS credit_amount_paid
FROM labours
LEFT JOIN labour_cashcredits ON labours.labour_master_id = labour_cashcredits.labour_master_id 
GROUP BY labours.labour_master_id
于 2012-12-19T11:43:13.013 回答