如何分组两次或限制一组?

时间:2016-06-22 01:01:44

标签: mysql sql

我有一个位置。一个位置有发票。发票有费。我想获得给定地点的特定月份的所有费用。

这是我能做的:

SELECT 
    STR_TO_DATE(CONCAT_WS('-', YEAR(invoices.invoiceDate) , MONTH(invoices.invoiceDate), '01'), '%Y-%m-%d') as invoiceMonth, 
    AVG(fees.amount) as averageMonthlyInvoice, 
    SUM(fees.amount) as totalMonthlyInvoice 
    from invoices as invoices 
    inner join fees as fees 
        on fees.invoiceId = invoices.id
    where invoices.locationId = 1
    group by invoiceMonth

第二个会给我一个位置的平均和总发票信息。我希望能够同时为所有地点执行此操作。 这就是我想要做的事情:

SELECT 
    invoices.locationId as locationId,
    STR_TO_DATE(CONCAT_WS('-', YEAR(invoices.invoiceDate) , MONTH(invoices.invoiceDate), '01'), '%Y-%m-%d') as invoiceMonth, 
    AVG(fees.amount) as averageMonthlyInvoice, 
    SUM(fees.amount) as totalMonthlyInvoice 
    from invoices as invoices 
    inner join fees as fees 
        on fees.invoiceId = invoices.id
    group by invoiceMonth, locationId

然而,最后一张只是平均和总计所有发票,而不是给我每个特定位置的信息。

1 个答案:

答案 0 :(得分:0)

也许使用ORDER BY (conditions)也可以帮助您获得所需的数据回报?