ORDER BY DATE 首先显示 NULL,然后显示最近的日期
我有一个执行 select 语句的存储过程。 我希望我的结果按日期字段排序,并首先显示具有 NULL 日期的所有记录,然后显示最近的日期。
该语句如下所示:
SELECT a,b,c,[Submission Date]
FROM someView
ORDER BY [Submission Date] ASC
现在,这将首先显示所有提交日期为 NULL 的记录,但是当我到达其中包含日期值的行时,它们不是视图中的最新日期。
如果我用 DESC 替换 ASC,那么我会按照我想要的顺序获得日期,但 NULL 值位于结果集的底部。
有什么方法可以构建我的查询,以便我可以在顶部显示空值,然后当存在日期值时,将它们按从最近到最旧的降序排列?
I have a stored procedure which executes a select statement. I would like my results ordered by a date field and display all records with NULL dates first and then the most recent dates.
The statement looks like this:
SELECT a,b,c,[Submission Date]
FROM someView
ORDER BY [Submission Date] ASC
Now this will display all records with NULL Submission Dates first, but when I get to rows that have date values in them, they are not the most recent dates in the view.
If I replace ASC with DESC, then I get the dates in the the order I want, but the NULL values are at the bottom of my result set.
Is there any way to structure my query so that I can display the null values at the top and then when there are date values, to order them descending most recent to oldest?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
@Chris,你几乎已经拥有它了。
[编辑:#Eppz 要求我调整上面的代码,如当前所示]
我个人更喜欢这样做,而不是创建“幻数”。 神奇数字几乎总是一个等待发生的问题。
@Chris, you almost have it.
[Edit: #Eppz asked me to tweak the code above as currently shown]
I personally prefer this a lot better than creating "magic numbers". Magic numbers are almost always a problem waiting to happen.
你可以这样做,将 NULL 放在底部:
You can do something like this put the NULL's at the bottom:
标准 SQL(ISO/IEC 9075-2:2003 或更高版本 - 2008)规定:
AFAIK,大多数 DBMS 实际上还不支持这一点。
Standard SQL (ISO/IEC 9075-2:2003 or later - 2008) provides for:
Most DBMS do not actually support this yet, AFAIK.
尝试
try
我知道这已经很旧了,但是当我发现它时,我注意到了已接受的解决方案, https://stackoverflow.com/a/821856/7177892 ,可以通过使 CASE 语句的结果为今天 (GETDATE()) 或实际日期来简化。
原文:
简化版:
I know this is old, but when I found it I noticed the accepted solution, https://stackoverflow.com/a/821856/7177892, could be simplified by making the result of the CASE statement be either today (GETDATE()) or the actual date.
Original:
Simplified:
我有另一个建议,可能比所有其他建议更简单:
对于 SQL Server,大多数选项都不起作用,除了案例选项。
我发现这对我来说确实很有效:
ORDER BY ISNULL(Submission_Date, GETDATE()) DESC
在查询的顺序位中,我将 GETDATE() 值分配给 null 的 Submittion_Date 值,并且顺序正确显示。
I have another suggestion that might be simpler than all the others:
For SQL Server, most of the options don't work, except the case ones.
I found that this actually works great to me:
ORDER BY ISNULL(Submission_Date, GETDATE()) DESC
In the order bit of the query, I assign the GETDATE() value to the Submittion_Date values that are null, and the order comes out correctly.
尝试这个
try this
假设提交日期小于当前日期时间
Assuming Submission Date less than current date-time