简体   繁体   中英

SQL: Order by date, only month and year given - Full Group on

I have an SQL database which is setted to full group on mode. My goal is to get the amount of rows (ID's) for every month. This is why I say Group By Datum . Because of the full group mode I cannot simply say Order By created_at . Because I have selected only %m.%Y . So I can only work with Datum which is cointaing my month and year.

I already tried to connect those values like CONCAT('DATE_FORMAT(created_at, '%Y-%m'), "-01 00:00:00") but also this isn't working... Even if I turn it into a UNIX Timestamp it isn't working: UNIX_TIMESTAMP(CONCAT('DATE_FORMAT(created_at, '%Y-%m'), "-01 00:00:00"))

I even tried this one: Order By Year(DATE_FORMAT(created_at, '%Y')), Month DATE_FORMAT(created_at, '%m') But it isn't also working...

How can I sort my result by month and year without changing the Select values? Sofar this is my actual SQL Query. Not working either.. I am nearly trying to find a solution since 1 hour...

SELECT COUNT(ID) AS Anzahl, DATE_FORMAT(created_at, '%m.%Y') AS Datum FROM leads WHERE created_at >= '2015-01-01' AND created_at <= '2018-01-01' AND shopID = 4184 GROUP BY Datum ORDER BY UNIX_TIMESTAMP(STR_TO_DATE(Datum, '%Y-%m-01 00:00:00'))

I would appreciate any kind of help! And no, I cannot change the Select values or turn off the full_group_mode .

ORDER BY DATE_FORMAT(created_at, '%Y'), date_format(created_at, '%M') desc

This will sort the results by year ascending then by month descending.

Take a look at this SQL Fiddle to see the query using MySql 5.6

The following will sort by year and then month in ascending order:

order by substring(datum,4,4), substring(datum,1,2)

sqlfiddle: http://sqlfiddle.com/#!9/16fab4/3

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