且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在SQL中按年份和月份排序

更新时间:2021-08-24 22:19:09

对年份和月份顺序进行排序基于您的示例查询
Based on your sample query
select billdate from test ORDER BY YEAR(billdate),Month(billdate)



您必须将列转换为日期才能获得正确的排序。例如。


You are going to have to convert the column to a date to get the correct ordering. E.g.

select billdate 
from test 
ORDER BY DATEPART(MM,SUBSTRING(billdate,1,4) + SUBSTRING(billdate, 6,3) + '01')



这是一个非常糟糕的方式 - billdate应该是日期或日期时间列,在这种情况下你可以做类似的事情。


This is a truly awful way to go about things - billdate should be a date or datetime column in which case you could do something like

select cast(DATEPART(YY,billdate) as varchar) + '_' + convert(char(3), datename(month, billdate))
from test 
ORDER BY billdate



这也很糟糕。

你应该做的是


Which is also pretty awful.
What you should be doing is

select billdate from test order by billdate

并在演示文稿(UI)层中对结果进行格式化

and doing the formatting of the result in the presentation (UI) layer


那是因为你是严重存储信息:您将其存储为字符串,这意味着比较将始终基于字符串:第一个不同的字符确定整个比较的结果。

如果存在,则可以执行此操作您将年份部分提取为字符串,然后将月份部分作为单独的字符串提取。然后,您可以使用JOIN到单独的表将短月份名称转换为数字,然后使用yera和minth值进行ORDER BY。

但是......它很笨拙,而且很差理念。每次你想要访问或使用该字段时,它也会变慢。

相反,将列更改为DATE或DATETIME然后它是微不足道的:

That's because you are storing information badly: you are storing it as a string, which means that the comparison will always be string based: the first different character determines the result of the whole comparison.
It is possible to do it if you extract the year portion as a string, and then month part as a separate string. You can then use a JOIN to a separate table to convert the short month name to a number, and then use the yera and minth values to ORDER BY.
But...it's clumsy, and a poor idea. It's also goign to be slow every time you want to access or use the field.
Instead, change the column to a DATE or DATETIME and then it's trivial:
SELECT BillDate FROM test 
ORDER BY DATEPART(yy, BillDate), DATEPART(mm, BillDate)