Doing a secondary sort by year in a SQL query

匿名 (未验证) 提交于 2019-12-03 10:24:21

问题:

So I have a table that with ID values and dates that looks something like this:

ID           Date 0001         1/1/2012 0002         1/2/2010 0002         1/2/2011 0001         1/1/2011 0001         1/1/2010 0002         1/2/2012

Basically, the ID values are unique to that year only - they reset the subsequent year.

I want to be able to sort by ID values and by dates, but I want to do the sorting so that the values are ordered by year. Just a regular sort of ID with a secondary date sort yields this:

ID           Date 0001         1/1/2010 0001         1/1/2011 0001         1/1/2012 0002         1/2/2010 0002         1/2/2011 0002         1/2/2012

But I would like a query that generates a table that looks like this:

ID           Date 0001         1/1/2010 0002         1/2/2010 0001         1/1/2011 0002         1/2/2011 0001         1/1/2012 0002         1/2/2012

Is this possible?

回答1:

How about this:

order by year(date), id


回答2:

SELECT * FROM .. ORDER BY DATEPART("yyyy",myDateColumn), ID



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!