我有一个包含大量日期时间条目的表。我想选择按降序日期顺序排序的不同MONTH YEAR字符串列表。例如,我想看看
October 2012
September 2012
June 2012
July 2011
查询需要是不同的,因为每个月/每天都有多个条目。
这就是我所拥有的
SELECT DISTINCT YEAR(DateRequested), datename(MONTH,[DateRequested])
FROM [dbo].[MyDateData]
ORDER BY YEAR(DateRequested), MONTH([DateRequested])
但是我收到了这个错误:
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
感觉就像我差不多但却无法正确理解这种语法。我正在使用SQL Server 2012 - 谢谢
答案 0 :(得分:3)
尝试;
SELECT monthYear FROM (
SELECT DISTINCT DATENAME(month,dateCol) + ' ' +
CONVERT(VARCHAR, DATEPART(year,dateCol)) monthYear,
CONVERT(varchar(6),dateCol, 112) orderCol
FROM yourTable ) A
ORDER BY CONVERT(INT,orderCol) desc
答案 1 :(得分:0)
您只需要确保ORDER BY行中的所有内容都在SELECT中。
答案 2 :(得分:0)
请改为尝试:
;WITH CTE
AS
(
SELECT DISTINCT
YEAR(DateRequested) "Year",
DATENAME(MONTH,[DateRequested]) "Month"
FROM YourDateTable
)
SELECT *
FROM CTE
ORDER BY "Year", "Month"