SQL Server 2008:如何按会计年度对Month列进行排序

时间:2016-06-03 18:33:38

标签: sql sql-server

任何人都可以帮我排序"月"财政年度以下脚本的列?例如,对于2016财年,' 07/15'应该是第一个和#06; 16/16'最后。谢谢!

SELECT 
    RIGHT(CONVERT(VARCHAR(8), closed_dt, 3), 5) AS "MONTH", 
    Count(facility_id) COUNT 
FROM   
    facility 
WHERE  
    closed_dt BETWEEN @FromDate AND @EndDate 
GROUP BY 
    facility_status, RIGHT(CONVERT(VARCHAR(8), closed_dt, 3), 5) 
HAVING 
    facility_status IN ( 'CLOSED' ) 

2 个答案:

答案 0 :(得分:2)

另一种选择是添加另一列

SELECT RIGHT(CONVERT(VARCHAR(8), closed_dt, 3), 5) AS [MONTH]
      ,Count(facility_id) as [COUNT]
      ,max(closed_dt) as SortCol
FROM   @facility 
WHERE  closed_dt BETWEEN @FromDate AND @EndDate 
GROUP  BY facility_status
         ,RIGHT(CONVERT(VARCHAR(8), closed_dt, 3), 5) 
HAVING facility_status IN ( 'CLOSED' ) 
Order by SortCol

答案 1 :(得分:0)

您在转换中使用'dd / mm / yy'样式。您只需要将最后两个字符转换为int作为排序:

ORDER BY  CAST(RIGHT(CONVERT(VARCHAR(8), closed_dt, 3), 2) as int),
RIGHT(CONVERT(VARCHAR(8), closed_dt, 3), 5)

这将按年份排序,然后是你的年龄......这有点草率,但是应该这样做。