在 SQL 中将季度年转换为月末日期
convert quarter-year to month-end date in SQL
我有时间列,值为 1Q1993
(QuarterYear),我想获取季度的月底日期(即 1993-03-31
)。请有人帮忙 SQL。我需要添加到 select 语句。
您可以提取年份,转换为日期,然后加上几个月并减去一天:
select (date(concat(right(col, 4), '-01-01') +
interval (left(col, 1) * 3 + 1) month -
interval 1 day
)
最简单的方法可能是 case
表达式:
select
concat(
right(mycol, 4),
'-'
case left(mycol, 1)
when '1' then '03-31'
when '2' then '06-30'
when '3' then '09-30'
when '4' then '12-30'
end
) as mydate
from mytable
这将重建 YYYY-MM-DD
格式的字符串,MySQL 会很乐意将其理解为日期。
你可以用这个。由于日期是固定的,不会移动
SET @date := "1Q1993"
SELECT CONCAT(SUBSTRING_INDEX(@date,'Q',-1),
CASE SUBSTRING_INDEX(@date,'Q',1)
WHEN 1 THEN '-03-31'
WHEN 2 THEN '-06-30'
WHEN 3 THEN '-09-30'
ELSE '-12-31' END)
| CONCAT(SUBSTRING_INDEX(@date,'Q',-1),
CASE SUBSTRING_INDEX(@date,'Q',1)
WHEN 1 THEN '-03-31'
WHEN 2 THEN '-06-30'
WHEN 3 THEN '-09-30'
ELSE '-12-31' END) |
| >:--------------------------------------------------------------------------------------->---------------------------------------------------------------------------------------->------- |
| 1993-03-31 |
db<>fiddle here
另一种方法:
date(concat(substring_index(qtr,'Q',-1),'-01-01')) + interval substring_index(qtr,'Q',1)*3 month - interval 1 day
https://dbfiddle.uk/?rdbms=mysql_5.5&fiddle=a0a4a86900d9d6537418602ae6153a66
我有时间列,值为 1Q1993
(QuarterYear),我想获取季度的月底日期(即 1993-03-31
)。请有人帮忙 SQL。我需要添加到 select 语句。
您可以提取年份,转换为日期,然后加上几个月并减去一天:
select (date(concat(right(col, 4), '-01-01') +
interval (left(col, 1) * 3 + 1) month -
interval 1 day
)
最简单的方法可能是 case
表达式:
select
concat(
right(mycol, 4),
'-'
case left(mycol, 1)
when '1' then '03-31'
when '2' then '06-30'
when '3' then '09-30'
when '4' then '12-30'
end
) as mydate
from mytable
这将重建 YYYY-MM-DD
格式的字符串,MySQL 会很乐意将其理解为日期。
你可以用这个。由于日期是固定的,不会移动
SET @date := "1Q1993"
SELECT CONCAT(SUBSTRING_INDEX(@date,'Q',-1), CASE SUBSTRING_INDEX(@date,'Q',1) WHEN 1 THEN '-03-31' WHEN 2 THEN '-06-30' WHEN 3 THEN '-09-30' ELSE '-12-31' END)
| CONCAT(SUBSTRING_INDEX(@date,'Q',-1), CASE SUBSTRING_INDEX(@date,'Q',1) WHEN 1 THEN '-03-31' WHEN 2 THEN '-06-30' WHEN 3 THEN '-09-30' ELSE '-12-31' END) | | >:--------------------------------------------------------------------------------------->---------------------------------------------------------------------------------------->------- | | 1993-03-31 |
db<>fiddle here
另一种方法:
date(concat(substring_index(qtr,'Q',-1),'-01-01')) + interval substring_index(qtr,'Q',1)*3 month - interval 1 day
https://dbfiddle.uk/?rdbms=mysql_5.5&fiddle=a0a4a86900d9d6537418602ae6153a66