我想按日期排序yyyy,mm。 我首先尝试使用VARCHARS:
GROUP BY (YEAR(join_date) AS VARCHAR(4)) + '-' + CAST(MONTH(join_date) AS VARCHAR(2))
但将它们转换为varchar意味着我的排序就像 2014.1 - 2014.11 - 2014.12 - 2014.2 我怎么能按年月顺序对它们进行适当的排序?
SELECT Year(join_date) + MONTH(join_date) AS Date, COUNT(*) AS Count
FROM X
WHERE mtype ='A' AND (join_date BETWEEN DATEADD(year, -5, GETDATE()) AND GETDATE())
GROUP BY YEAR(join_date) + MONTH(join_date)
ORDER BY Date ASC
答案 0 :(得分:2)
您只是不需要将它们转换为varchar,YEAR
和MONTH
返回ints:
SELECT Year(join_date) As JoinedYear, MONTH(join_date) AS JoinedMonth, COUNT(*) AS Count
FROM X
WHERE mtype ='A' AND (join_date BETWEEN DATEADD(year, -5, GETDATE()) AND GETDATE())
GROUP BY YEAR(join_date), MONTH(join_date)
ORDER BY YEAR(join_date) ASC, MONTH(join_date) ASC