我试图选择一个字符串的最小值,但是由于sql按字典顺序自动排序,而不是我所需的正确顺序。
我目前有3个季节,我想选择最小数量/最小数量。我目前拥有的代码是:
Select distinct season from table1 order by season desc;
当前输出的顺序是:
Spring19
Autumn19
Autumn18
但是我需要它按照季节的顺序排列:
Autumn18
Spring19
Autumn19
是否可以在不实际更改文本格式的情况下将格式更改为“日期”?还是有其他方法可以做到这一点?
谢谢:)
答案 0 :(得分:1)
大多数数据库支持right()
功能(如果不支持,则它们具有相似的功能,但名称不同)。
所以,这应该起作用:
Select distinct season
from table1
order by right(season, 2) asc, season desc;
答案 1 :(得分:0)
with seasoncte (season_number, season_year, season) as (
select case when left(season, length(season) -2) = "Spring" then 1
when left(season, length(season) -2) = "Summer" then 2
when left(season, length(season) -2) = "Autumn" then 3
when left(season, length(season) -2) = "Winter then 4
end as season_number,
cast(right(season,2 as int) as season_year,
season
from table1
), seasoncte2 (season_number, season_year, season) as (
select season_number
case when season_year < 39 then 2000 + season_year
case else then 1900 + season_year
end,
season
from seasoncte
)
select t1.season
from table1 t1
join seasoncte2 cte
on t1.season = cte.season
order by cte.season_year, cte.season_number
代码可能需要根据SQL方言进行调整。
Op没有指定。或提供rextester链接,以便可以测试代码。