日期转换为月 - 年作为新日期SQL,按新日期排序

时间:2013-10-27 13:00:07

标签: sql sql-server sql-server-2008 date

我正在尝试的查询:

SELECT Datename(month, c1.date) + ' - ' 
       + Datename(year, c1.date) AS newdate 
FROM   cust_ledger AS c1 
WHERE
GROUP BY Datename(month, c1.date) + ' - ' 
       + Datename(year, c1.date)
ORDER BY newdate

返回:

December-2013
Janyuary-2013
November-2013
Octomber-2013

我希望对结果进行排序:

Janyuary-2013
Octomber-2013
November-2013
December-2013

3 个答案:

答案 0 :(得分:1)

group by中加入要排序的'字段'并按其排序。

SELECT Datename(month, c1.date) + ' - ' 
       + Datename(year, c1.date) AS newdate 
FROM   cust_ledger AS c1 
GROUP BY Datename(month, c1.date) + ' - ' 
       + Datename(year, c1.date),Datepart(year, c1.date),Datepart(Month, c1.date)
ORDER BY Datepart(year, c1.date),Datepart(Month, c1.date)

答案 1 :(得分:0)

SELECT TOP X *
FROM myTable
ORDER BY
  CASE
       WHEN LEFT(Col , LEN(Col) - 5)= 'December' THEN 12
       WHEN LEFT(Col , LEN(Col) - 5)= 'November' THEN 11
       WHEN LEFT(Col , LEN(Col) - 5)= 'October' THEN 10
       WHEN LEFT(Col , LEN(Col) - 5)= 'September' THEN 9
       WHEN LEFT(Col , LEN(Col) - 5)= 'August' THEN 8
       WHEN LEFT(Col , LEN(Col) - 5)= 'July' THEN 7
       WHEN LEFT(Col , LEN(Col) - 5)= 'June' THEN 6
       WHEN LEFT(Col , LEN(Col) - 5)= 'May' THEN 5
       WHEN LEFT(Col , LEN(Col) - 5)= 'April' THEN 4
       WHEN LEFT(Col , LEN(Col) - 5)= 'March' THEN 3
       WHEN LEFT(Col , LEN(Col) - 5)= 'February' THEN 2
       WHEN LEFT(Col , LEN(Col) - 5)= 'January' THEN 1

  END ASC

在某些情况下,例如'Janyuary''Octomber',您的拼写会有点滑稽,请记住这一点,此代码应该适用于您:)

查看此处的搜索结果 sqlfiddle

答案 2 :(得分:-1)

尝试order by c1.日期::

    select 
CONCAT(DATENAME(`month`,c1.`date`),' - ',DATENAME(`year`, c1.`date`)) as newdate 
from cust_ledger as c1 
group by YEAR(ci.`date`),MONTH(c1.`date`)
order by c1.`date`