0

我有带有日期字段的表格并转换为月份和年份(2 个单独的列)。我无法排序

Month    Year
12        2011
11        2011
2         2012
1         2012

如果我写查询。它给出了

  Month       Year
   1          2012
   2          2012
   11         2011
   12         2011

但是我需要像下面这样

  Month          Year
   11         2011
   12         2011
    1         2012
    2         2012

这里按月分组,我不想显示日期字段

请帮忙

4

2 回答 2

2
select datepart(month, DateCol) as [Month],
       datepart(year, DateCol) as [Year]
from YourTable
order by [Year], [Month]

SQL小提琴

如果你想按月分组

select datepart(month, DateCol) as [Month],
       datepart(year, DateCol) as [Year]
from YourTable
group by datepart(month, DateCol),
         datepart(year, DateCol)
order by [Year], [Month]

SQL小提琴

于 2013-03-08T07:12:08.493 回答
2

这是你可以做的:

;WITH CTE
AS
(
    SELECT *,
    ROW_NUMBER() OVER ( PARTITION BY YEAR ORDER BY MONTH) RN
FROM YourTable
)

SELECT * FROM CTE  
ORDER BY YEAR, RN

SQL 小提琴演示

实际上,一种更直接的方式是,

SELECT * FROM YourTable
ORDER BY YEAR, MONTH
于 2013-03-08T07:18:23.443 回答