排序不同的日期列

时间:2009-06-01 10:01:16

标签: sql sql-server tsql

我需要从日期列开始的不同年份和月份,它将按相同的列排序。

我的日期库存值为(YYYY / MM / DD)

2007/11/7
2007/1/8
2007/11/4
2007/12/3
2008/10/4
2009/11/5
2008/5/16
查询后

应该是

2007/1/1
2007/11/1
2007/12/1
2008/5/1
2008/10/1
2009/11/1

这似乎不起作用

SELECT distinct (cast(year(datecol) as nvarchar(20) ) +
       '/'+ cast(month(datecol) as nvarchar(20) ) + '/1') as dt1 
FROM Table 
ORDER BY dt1

3 个答案:

答案 0 :(得分:2)

这样的事情可以在MS SQL Server上运行:

select 
    distinct 
    dateadd(day, -1 * DAY(datefield) + 1, datefield)
From
    datetable
order by
    dateadd(day, -1 * DAY(datefield) + 1, datefield) 

DATEADD函数调用基本上从当前日期减去(第-1天)DAYS - >你总是得到那个日期的第一个月。

按它排序,你就完成了! : - )

此外,您还可以将此功能作为“计算列”添加到表中,然后使用它来轻松访问:

alter table yourTable 
  add FirstOfMonth As DATEADD(day, -1 * DAY(datefield) + 1, datefield) persisted

然后您的查询会更简单:

SELECT DISTINCT FirstOfMonth
FROM YourTable
ORDER BY FirstOfMonth

马克

答案 1 :(得分:0)

在SqlServer中处理日期时,请避免像这样使用cast - 结果格式将根据服务器配置而改变。

而是使用convert并选择一种格式(例如112),将前导零添加到月份。

答案 2 :(得分:0)

阿尼尔, 你还有时间参加约会吗?您使用哪种数据类型的列?你是 使用DateTime dataType或Char?

这对我有用

SELECT DISTINCT (DateField) AS Date FROM DateTable ORDER BY 1
相关问题