简体   繁体   中英

CASE Statement between dates

For my EntryDate column I've been trying to successfully separate my data by month and into specific names '2013_04','2013_05' etc, so I can later group my data by it also. This code has thus far been unsuccessful, how can it be changed to work?

CASE
WHEN EntryDate BETWEEN '2013-04-01' AND '2013-04-30' THEN '2013_04'
WHEN EntryDate BETWEEN '2013-05-01' AND '2013-05-31' THEN '2013_05'
WHEN EntryDate BETWEEN '2013-06-01' AND '2013-06-30' THEN '2013_06'
END

Thank you.

You can use DATE_FORMAT function:

DATE_FORMAT(EntryDate, '%Y_%m')

http://dev.mysql.com/doc/refman/5.6/en/date-and-time-functions.html#function_date-format

I would use the year() and month() functions, just because this is common across databases:

CONCAT_WS('_', YEAR(EntryDate), MONTH(EntryDate))

However, DATE_FORMAT() is also a good solution.

DATE_FORMAT()是最佳选择,但是如果字符串函数和CONVERT可以使用不同的数字

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-2025 STACKOOM.COM