我有一个带有日期字段的表,并转换为月和年(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
这里按月分组,我不想显示日期字段
请帮忙
答案 0 :(得分:2)
select datepart(month, DateCol) as [Month],
datepart(year, DateCol) as [Year]
from YourTable
order by [Year], [Month]
如果你想按月分组
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]
答案 1 :(得分:1)
这是你可以做的:
;WITH CTE
AS
(
SELECT *,
ROW_NUMBER() OVER ( PARTITION BY YEAR ORDER BY MONTH) RN
FROM YourTable
)
SELECT * FROM CTE
ORDER BY YEAR, RN
实际上还有一个明星前进的方式,
SELECT * FROM YourTable
ORDER BY YEAR, MONTH