按年和月分组数据

时间:2018-07-30 13:26:02

标签: mysql group-by

我有一个包含4列的表格:

 1. customerID
 2. dateAdded
 3. productID
 4. quantity

dateAdded的格式如下:20180730YearMonthDay)。

我想按年和月对表中的行进行分组。

我尝试了下面的代码,但没有用。我仍然看到重复的年份和月份重复但日期不同的行。

SELECT dateAdded
     , SUM(quantity) 
  FROM testTable 
 GROUP 
    BY DATE_FORMAT(dateAdded, '%Y%m')
     , dateAdded 
 ORDER 
    BY dateAdded DESC

有什么解决方法吗?

谢谢

3 个答案:

答案 0 :(得分:0)

不要按不希望对数据进行分组的分组。由于您提供dateAdded作为要与之分组的参数,因此它会将数据按dateAdded进行拆分,因此从年月分组中没有任何收益。从select / groupby中删除用于分组的列,如下所示:

SELECT DATE_FORMAT(dateAdded, '%Y%m')
     , SUM(quantity) 
FROM testTable 
GROUP BY 
     DATE_FORMAT(dateAdded, '%Y%m')

答案 1 :(得分:0)

如果您将dateAdded存储为20180730,看起来像是一个字符串,那么它将无法与DATE_FORMAT函数一起使用,则可以改用SUBSTRING

类似

SELECT dateAdded, SUM(quantity), SUBSTRING(dateAdded, 1, 6) as d 
  FROM testTable 
 GROUP BY d
 ORDER BY dateAdded DESC

答案 2 :(得分:0)

使用yearmonth函数

 SELECT Year(dateAdded) as YearOfDate,Month(dateAdded) as MonthOfdate,
         , SUM(quantity) as Qty
      FROM testTable 
     GROUP 
        BY Year(dateAdded), Month(dateAdded) 
     ORDER  BY dateAdded DESC