使用group by从其他表中选择sum

时间:2016-01-20 16:24:56

标签: mysql join group-by

我有两张桌子"发票"和" invoices_account"

按查询

SELECT DATE_FORMAT(inv_created, '%Y') as 'year',
       COUNT(*) as 'total' 
FROM invoices as i 
WHERE inv_way = "OUT" 
GROUP BY DATE_FORMAT(inv_created, '%Y')

我每年都会收到发票金额:

2011 | 80
2012 | 120

等等。

我需要的是获取" invoices_account"。" inv_total"的所有条目的摘要。在第一个查询中按年份。关系是1:1。这意味着,2011年的80张发票在" invoices_account"中有80行。我需要有这样的东西

2011 | 80  | 1.000.000 €
2012 | 120 | 230.000.000 €

1 个答案:

答案 0 :(得分:1)

检查 INNER JOIN

SELECT DATE_FORMAT(inv_created, '%Y') as 'year',
       COUNT(*) as 'total', 
       SUM(ia.inv_total) as money_total
FROM invoices as i 
JOIN invoices_account ia
  ON i.id = ia.id
WHERE inv_way = "OUT" 
GROUP BY DATE_FORMAT(inv_created, '%Y')