如何将两个不同的表与两个不同的groupby相加

时间:2017-10-10 10:00:26

标签: php mysql sql

我有两个名为workstuff的表,两个表都有相同的字段 -  companyqualityquantity

我需要按quantitycompany分组所有quality工作的总和,并将所有quantity项内容的总和加入表中companyquality

我没有得到预期的结果。 SQLfiddel  http://sqlfiddle.com/#!9/eea577/6

2 个答案:

答案 0 :(得分:1)

工作查询

select st.company,st.quality,st.quantitys - ct.quantitys as balance from
(select company,quality,sum(quantity) as quantitys from stuff
 group by quality,company) as st join (select company,quality,
 sum(quantity) as quantitys from work group by quality,company)
 as ct on `ct`.`company` = `st`.`company` and ct.quality = st.quality group by quality,company

你错过了加入的质量状况

答案 1 :(得分:0)

尝试以下方法:

SELECT tableA.ID, tableA.`Year`, tableA.`Month`,  
       tableA.`Type`, tableA.instrument, 
       tableA.totalAmount, tableB.totalInstrument
FROM
(
    SELECT  a.ID, a.`Year`, a.`Month`, 
            b.`Type`, b.instrument, 
            SUM(b.`amount`) totalAmount
    FROM    `date` a
                INNER JOIN `transactions` b
                    ON a.ID = b.id
    GROUP BY b.`Type
) tableA
INNER JOIN
(
    SELECT  a.ID, a.`Year`, a.`Month`, 
            b.`Type`, b.instrument, 
            SUM(b.`instrument`) totalInstrument
    FROM    `date` a
                INNER JOIN `transactions` b
                    ON a.ID = b.id
    GROUP BY a.`Year`, a.`Month`
) tableB ON tableA.ID = tableB.ID AND
            tableA.`Year` = tableB.`Year` AND
            tableA.`Month` = tableB.`Month`