0
votes

convertir un trimestre d'année en date de fin de mois en SQL

J'ai la colonne de temps, la valeur est 1Q1993 (QuarterYear), et je voudrais obtenir la date de fin de mois du trimestre (qui est 1993-03-31 ). S'il vous plaît, quelqu'un pourrait-il aider avec le SQL. J'ai besoin d'ajouter à une instruction select.


0 commentaires

4 Réponses :


0
votes

Vous pouvez utiliser extraire l'année, convertir en une date, puis ajouter quelques mois et soustraire un jour:

select (date(concat(right(col, 4), '-01-01') +
        interval (left(col, 1) * 3 + 1) month -
        interval 1 day 
       )


0 commentaires

1
votes

L'approche la plus simple pourrait être une expression de 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 

Cela reconstruit une chaîne au format YYYY-MM-DD , que MySQL comprendra volontiers comme une date.


0 commentaires

1
votes

Vous pouvez utiliser ceci. Comme les dates sont fixes et ne bougent pas

| 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                                                                                                                                                                              |
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)
SET @date := "1Q1993"

db <> violon ici


0 commentaires

1
votes

Une autre approche:

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


0 commentaires