使用与分组数据行的连接

时间:2012-09-07 10:39:18

标签: mysql database join left-join

我有两个表,invoicesdeposits

他们看起来有点像这样:

发票

id    |    paymentType     |     grossTotal   |    dateTime
1     |         Cash       |        1000      |   UNIX TIME    
2     |         Card       |        1350      |   UNIX TIME   
3     |         Card       |        1250      |   UNIX TIME   
4     |         Card       |        750       |   UNIX TIME 

矿床

id    |    paymentType     |       invNo      |    dateTime    |     amount
1     |         Cash       |         1        |    UNIX TIME   |       150
2     |         Card       |         2        |    UNIX TIME   |       350

存款总是过去的日期,发票日期将是today,因此我想确定今天在发票上支付的余额,即invoices.grossTotal - deposits.amount,并按付款清单类型。

因此,在上面的表格示例中,发票1上支付了850英镑,发票2上支付了1000英镑,这很容易实现每个一行或两行,但在分组付款类型和存款发票时我被卡住了......

SELECT 
   invoices.id, 
   sum(grossTotal)-IFNULL(depositsCheck.previouslyPaid,0) as todayTotal, 
   depositsCheck.previouslyPaid, sum(grossTotal) as grossTotal  
FROM `invoices`    
    LEFT JOIN (SELECT SUM(amount) as previouslyPaid, invNo 
    FROM deposits 
    GROUP BY invNo) depositsCheck ON depositsCheck.invNo=invoices.id 
GROUP BY  invoices.paymentType ORDER BY id DESC

上面的SQL查询适用于使用CASH支付的项目,但不适用于卡支付,因为,分组invoices.paymentType表示来自id表的invoices列已不再正确,因此JOIN如果此行的id与之无关,则会失败。

如何运行上述查询,但确保我可以在发票的任何实例上join deposits表,按照与分组列ID记录匹配的付款类型进行分组?

我正在使用mySql,所以请发布MySql可以做的联接! :d

1 个答案:

答案 0 :(得分:0)

问题在于,当您使用GROUP BY时,您只能SELECT聚合以及您分组的列。

invoices.id是您尝试选择的列,但未进行分组。我想您可能希望将此列添加到GROUP BY子句中。

SELECT 
   invoices.id, 
   sum(grossTotal)-IFNULL(depositsCheck.previouslyPaid,0) as todayTotal, 
   depositsCheck.previouslyPaid, sum(grossTotal) as grossTotal  
FROM `invoices`    
    LEFT JOIN (SELECT SUM(amount) as previouslyPaid, invNo 
    FROM deposits 
    GROUP BY invNo) depositsCheck ON depositsCheck.invNo=invoices.id 
GROUP BY  invoices.paymentType, invoices.id ORDER BY id DESC

对于您提供的示例表,它可能会给出:

id    |    paymentType     |     grossTotal   |    dateTime   |   previouslyPaid
1     |         Cash       |        1000      |   UNIX TIME   |       150
2     |         Card       |        1350      |   UNIX TIME   |       350
3     |         Card       |        1250      |   UNIX TIME   |         0
4     |         Card       |        750       |   UNIX TIME   |         0

但总的来说,你会有类似的东西:

id    |    paymentType     |     grossTotal   |    dateTime   |   previouslyPaid
1     |         Cash       |        1000      |   UNIX TIME   |       150
1     |         Card       |        1000      |   UNIX TIME   |       300
2     |         Cash       |        1350      |   UNIX TIME   |       350
2     |         Card       |        1350      |   UNIX TIME   |       350

如上所示,对于发票1,150是现金支付,300是通过卡支付。