MySQL查询按月分组

时间:2017-11-23 14:39:10

标签: mysql

我有一个MySQL查询,输出如下数据:

Output Example

这是我用来生成输出的当前查询。

SELECT *
FROM (SELECT staff.firstname AS stafffirstname
             , staff.surname AS staffsurname
             , transactions.total
             , transactions.description
             , transactions.datetime
             , transactions.ID
             , (@runningtotal := @runningtotal + transactions.total) AS balance
      FROM transactions
        LEFT JOIN staff ON transactions.createdbyID = staff.ID
      WHERE transactions.tenancyID = ?
      ORDER BY transactions.datetime
               , transactions.ID) FullResults
ORDER BY FullResults.datetime
         , FullResults.ID 
LIMIT ? , ?;

因此,它正在进行完整查询以构建运行余额,然后选择要输出的子集。我正在使用的表支持分页。

我如何获取数据并按月将所有子项组合在一起? IE,所有11月份的常备费用应该只有一行。并且所有11月的使用费应该只有一行。

更新

到目前为止,这是我在JustLukas的帮助下的查询。

SELECT
  FullResults.*
FROM
  (SELECT
      staff.firstname AS stafffirstname,
      staff.surname AS staffsurname,
      transactions.total,
      transactions.description,
      transactions.datetime,
      transactions.ID,
      (@runningtotal := @runningtotal + transactions.total) AS balance,
      Concat(CONVERT(IfNull(transactions.meterID, ''), CHAR), ";", CONVERT(transactions.typeID, CHAR), ";",
      Left(MonthName(transactions.datetime), 3), CONVERT(Year(transactions.datetime), CHAR)) AS GroupingField
    FROM
      transactions
      LEFT JOIN staff ON transactions.createdbyID = staff.ID
    WHERE
      transactions.tenancyID = 2631
    ORDER BY
      transactions.datetime,
      transactions.ID) FullResults
GROUP BY
  FullResults.GroupingField

如何获取每个组的SUM(transaction.total)?目前,它只显示每组中第一行的总数。

由于 丹

2 个答案:

答案 0 :(得分:0)

尝试使用下面的代码,技巧是将日期转换为可分组的东西。不确定您在Where transactions.tenancyID = ?

部分中的含义
select * from 
   (Select 
      staff.firstname As stafffirstname, 
      staff.surname As staffsurname, 
      transactions.total, 
      transactions.description, 
      left(Datename(month,transactions.datetime),3) + char(39) + right(Datename(year,transactions.datetime),2) as 'Period',
      transactions.ID, 
      (@runningtotal:= @runningtotal + transactions.total) as balance 
    From transactions Left Join staff On transactions.createdbyID = staff.ID 
    Where transactions.tenancyID = ? 
    Order By transactions.datetime, transactions.ID
   ) FullResults 
Group By 
  FullResults.Period,  
  transactions.description, 
  transactions.ID,
  FullResults.stafffirstname,
  FullResults.staffsurname

答案 1 :(得分:0)