简体   繁体   中英

Group data by Year and Month

I have a table with 4 columns:

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

The format of dateAdded is like this: 20180730 ( YearMonthDay ).

I want to group the rows in the table by year and month.

I tried the code below but it doesn't work. I still see rows with the same year and month repeated, but different day.

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

Any idea how to fix this?

Thank you

Do not group by what you do not want the data to be grouped. Since you provide dateAdded as a parameter to be grouped with, it splits the data by dateAdded and you gain nothing out of year-month grouping. Remove the columns from select/groupby that you use for grouping like this:

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

If you store dateAdded as 20180730, looks like it's a string, so it wont work with DATE_FORMAT function, you can use SUBSTRING instead

something like

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

use year and month function

 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM