使用GROUP BY

时间:2017-07-15 13:27:52

标签: mysql sql group-by sum subquery

我有两张桌子:发票项目

发票

id | timest

id | invoice_id | price | qty

很明显,发票上可能有多个项目 - items.invoice_id = invoices.id

我有以下查询,选择所有发票及其项目的总和:

SELECT id, DATE_FORMAT(FROM_UNIXTIME(inv.time), "%Y-%m" ) AS _period, 
(SELECT SUM(it.price*it.quantity) FROM items AS it WHERE it.invoice_id=inv.id) as total 
FROM `invoices` `inv`

这会生成如下内容:

id| _period | total
-------------------
1 | 2014-06 | 100
4 | 2014-06 | 200
5 | 2014-07 | 660
6 | 2014-07 | 300
7 | 2014-07 | 30
9 | 2015-02 | 225

现在我想按时间段对其进行分组,以便输出:

_period | qty | total_price
---------------------------
2014-06 |  2  | 300
2014-07 |  3  | 990
2015-02 |  1  | 224

我可以轻松地将数量字段用作

SELECT DATE_FORMAT(FROM_UNIXTIME(inv.time), "%Y-%m" ) AS _period,
COUNT(inv.id) as qty
FROM `invoices` `inv`
GROUP BY _period

但我无法弄清楚如何对total_price字段进行类似的操作,这是由子查询虚拟字段产生的?有没有人有任何想法?

谢谢!

2 个答案:

答案 0 :(得分:0)

您应该使用LEFT JOINGROUP BY

执行此操作
SELECT DATE_FORMAT(FROM_UNIXTIME(i.time, '%Y-%m') AS _period, 
       COUNT(DISTINCT i.id) as num_invoices
       SUM(i.price * it.quantity) as total
FROM invoices i LEFT JOIN
     items it
     ON it.invoice_id = i.id
GROUP BY _period
ORDER BY _period;

答案 1 :(得分:0)

试试这个

SELECT InnerTable._period, Count(InnerTable.id) as id, Sum(InnerTable.total) as total FROM
    (SELECT id, DATE_FORMAT(FROM_UNIXTIME(inv.time), "%Y-%m" ) AS _period, 
(SELECT SUM(it.price*it.quantity) FROM items AS it WHERE it.invoice_id=inv.id) as total 
FROM `invoices` `inv`) as InnerTable FROM GROUP BY InnerTable._period.

从查询中创建子表,然后将group by放在上面。