简体   繁体   English

SQL按日期和月份选择查询顺序

[英]SQL select query order by day and month

Let's pretend today is the 3rd of February. 让我们假装今天是2月3日。

And I have a table: 我有一张桌子:

CREATE TABLE devotion
(
  id serial NOT NULL,
  date timestamp without time zone
}

And I have 4 records: 我有4条记录:

id date
1  2013-01-01
2  2013-02-02
3  2013-03-03
4  2013-04-04

I want to build a select query that would return all records in the following order (ordered by date, but upcoming dates first, passed dates appended to the end of the list) : 我想构建一个选择查询,该查询将按以下顺序返回所有记录(按日期排序,但首先是即将到来的日期,传递日期附加到列表末尾):

id date
3  2013-03-03 (upcoming dates first)
4  2013-04-04
1  2013-01-01 (passed dates appended to the end of the list)
2  2013-02-02

All records have the same year. 所有记录都具有相同的年份。 In fact, year is not important, only day and month are. 事实上,一年并不重要,只有日和月。 If you can suggest a better structure, you are very welcome. 如果你能建议一个更好的结构,非常欢迎你。

order by case when date1 > now() then 0 else 1 end case, date1

将给出3,4,1,2的顺序

Simpler: 更简单:

ORDER BY (date1 < now()), date1

You can just order by the boolean value of the expression (date1 < now()) . 您可以按表达式的布尔值(date1 < now())排序。
FALSE sorts before TRUE sorts before NULL . FALSETRUE之前排在NULL之前。

Here is another solution. 这是另一种解决方案。 Ofcourse above answer is good enough. 当然,上述答案已经足够好了。 You can't assume today is Feb 3rd since we are taking Now() which stand for Feb 2nd . 您不能假设今天是2月3日,因为我们采用的是Now() ,它表示Feb 2nd So I used demo data 2013-02-01 . 所以我使用了演示数据2013-02-01 And this answer is mainly depending on your ID . 而这个答案主要取决于您的ID To say that ID is sequential so is the date. 可以说ID是顺序的,日期也是如此。 Anyone is free to comment on the dodgy part of this logic .. 任何人都可以自由评论这个逻辑的狡猾部分 ..

MYSQL DEMO MYSQL演示

select id, `date`,
case when `date` > Date_Format(Now(),'%Y-%m-%d')
then id-3
else id+2 end as x
from demo
order by x asc
;

| ID |                            DATE | X |
--------------------------------------------
|  3 |    March, 03 2013 00:00:00+0000 | 0 |
|  4 |    April, 04 2013 00:00:00+0000 | 1 |
|  1 |  January, 01 2013 00:00:00+0000 | 3 |
|  2 | February, 01 2013 00:00:00+0000 | 4 |

如果您使用的是MySQL,我会说只使用RIGHT ,但以下内容应在psql上运行:

SELECT * FROM devotion ORDER BY substring(to_char( date, 'YYYY-MM-DD') from char_length(to_char( date, 'YYYY-MM-DD')) - 5)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM