2

我有一个包含大量日期时间条目的表。我想选择按日期降序排列的不同 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 - 谢谢

4

3 回答 3

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
于 2012-12-17T13:46:04.830 回答
0

您只需要确保 ORDER BY 行中的所有内容也在您的 SELECT 中。

于 2012-12-17T13:43:03.397 回答
0

试试这个:

;WITH CTE
AS
(
  SELECT  DISTINCT 
     YEAR(DateRequested) "Year",
     DATENAME(MONTH,[DateRequested]) "Month"
  FROM YourDateTable
) 
SELECT * 
FROM CTE 
ORDER BY "Year", "Month"

SQL 小提琴演示

于 2012-12-17T13:47:12.540 回答