在 MySQL 查询中将字符串格式化为日期
Format a string to a date in MySQL query
我有一个table如下所示,日期列是一个字符串(MMMM-yyyy)。
我想select ID 的最新行。对于 ID # 2,最晚日期为 2020 年 8 月,价格为 45.40
ID Date Price
2 August-2020 45.40
2 July-2020 42.30
我已经尝试了 format(date, 'MMMM-yyyy) as formatted date
和 STR_TO_DATE(date, '%MMMM-%yyyy')
,但我无法将其转换为日期,因此无法订购该专栏。我想以这种格式保留日期,我只需要为我的查询订购它。
使用str_to_date()
将字符串转换为日期;需要一个小技巧来使原始值在转换前成为完整的日期字符串,因此:
str_to_date(concat(date, '-01'), '%M-%Y-%d')
要根据每个 ID 的最新日期过滤 table,您可以这样做:
select t.*
from mytable t
where date = (
select date
from mytable t1
where t1.id = t.id
order by str_to_date(concat(date, '-01'), '%M-%Y-%d') desc
limit 1
)
您需要为 MySQL 使用正确的格式说明符。我希望这会起作用:
select STR_TO_DATE('August-2020', '%M-%Y')
但是,您似乎需要:
select str_to_date(concat('01-', 'August-2020'), '%d-%M-%Y')
Here 是一个 db<>fiddle.
我有一个table如下所示,日期列是一个字符串(MMMM-yyyy)。
我想select ID 的最新行。对于 ID # 2,最晚日期为 2020 年 8 月,价格为 45.40
ID Date Price
2 August-2020 45.40
2 July-2020 42.30
我已经尝试了 format(date, 'MMMM-yyyy) as formatted date
和 STR_TO_DATE(date, '%MMMM-%yyyy')
,但我无法将其转换为日期,因此无法订购该专栏。我想以这种格式保留日期,我只需要为我的查询订购它。
使用str_to_date()
将字符串转换为日期;需要一个小技巧来使原始值在转换前成为完整的日期字符串,因此:
str_to_date(concat(date, '-01'), '%M-%Y-%d')
要根据每个 ID 的最新日期过滤 table,您可以这样做:
select t.*
from mytable t
where date = (
select date
from mytable t1
where t1.id = t.id
order by str_to_date(concat(date, '-01'), '%M-%Y-%d') desc
limit 1
)
您需要为 MySQL 使用正确的格式说明符。我希望这会起作用:
select STR_TO_DATE('August-2020', '%M-%Y')
但是,您似乎需要:
select str_to_date(concat('01-', 'August-2020'), '%d-%M-%Y')
Here 是一个 db<>fiddle.