根据年份和月份进行排序。我有一个专栏期间。
其持续日期为 2016年1月至 APR-2018 。
我想根据近年来排序,然后月份也需要排序。
结果应如下所示:
我做了类似的事,但它有一个问题:
Cast(Year(cast(Q.Column Name as small date time)) as char(4)) + '-' + CASE WHEN Month(cast (Q.Column Name as small date time)) < 10 THEN '0' ELSE '' END + cast(Month(cast (Q.Column Name as small date time)) as char(2))
提前谢谢
答案 0 :(得分:0)
您可以使用ORDER BY
使用CAST
和DATEPART
分别针对年份和月份的订单{/ 1}}:
declare @tmp table ([period] varchar(10))
insert into @tmp values
('Jan-2016'), ('Feb-2016'), ('Mar-2016'), ('Apr-2016'), ('May-2016'), ('Jun-2016'), ('Jul-2016'), ('Aug-2016'), ('Sep-2016'), ('Oct-2016'), ('Nov-2016'), ('Dec-2016'), ('Jan-2017'), ('Feb-2017'), ('Mar-2017'), ('Apr-2017'), ('May-2017'), ('Jun-2017'), ('Jul-2017'), ('Aug-2017'), ('Sep-2017'), ('Oct-2017'), ('Nov-2017'), ('Dec-2017'), ('Jan-2018'), ('Feb-2018'), ('Mar-2018'), ('Apr-2018')
select *
from @tmp
order by DATEPART(year, cast( '1-' + [period] as date)) desc,
DATEPART(month,cast( '1-' + [period] as date)) asc
左侧是原始订单,右侧是order by
:
在你的情况下:
select *
from YOUR_TABLE_NAME
order by DATEPART(year, cast( '1-' + [period] as date)) desc,
DATEPART(month,cast( '1-' + [period] as date)) asc