我在SQL Server 2012中有一个日期时间类型列。我想显示按该列升序排序的列的唯一日期部分。
我尝试了这个查询,但它按字符串类型排序。必须有一个简单的查询,但我想念它。
select distinct(convert(varchar, CreatedDate, 101)) from sometable order by 1
更新
我正在添加DDL语句。我认为这是一个简单的查询,快速简单的答案。
CREATE TABLE Test
(
[CreatedDate] [datetime] NULL
)
INSERT INTO [Test]([CreatedDate])
VALUES(CAST('20161231 14:00:00.000' as DATETIME))
INSERT INTO [Test]([CreatedDate])
VALUES(CAST('20170101 12:00:00.000' as DATETIME))
INSERT INTO [Test]([CreatedDate])
VALUES(CAST('20170101 11:00:00.000' as DATETIME))
INSERT INTO [Test]([CreatedDate])
VALUES(CAST('20170101 10:00:00.000' as DATETIME))
INSERT INTO [Test]([CreatedDate])
VALUES(CAST('20170201 03:00:00.000' as DATETIME))
INSERT INTO [Test]([CreatedDate])
VALUES(CAST('20160403 02:00:00.000' as DATETIME))
预期结果:
04/03/2016
12/31/2016
01/01/2017
02/01/2017
答案 0 :(得分:2)
如果我没记错的话,你需要做这样的事情:
select convert(varchar, CreatedDate, 101)
from (
select distinct convert(date, CreatedDate) as CreatedDate
from sometable
) X
order by CreatedDate
因为您无法按照您用于区别的不同字段进行排序。
答案 1 :(得分:1)
将distinct
更改为group by
。这将允许您使用原始列进行排序:
<击> 撞击>
<击>SELECT CONVERT(char(10), CreateDate, 101)
FROM someTable
GROUP BY CONVERT(char(10), CreateDate, 101)
ORDER BY AVG(CreateDate)
击> <击> 撞击>
感谢Juan Carlose Oropeza在rextester中创建演示 - 我想出了seems to be working fine:
的解决方案SELECT CONVERT(char(10), CAST(CreatedDate as Date), 101)
FROM Test
GROUP BY CAST(CreatedDate as Date)
ORDER BY CAST(CreatedDate as Date)
答案 2 :(得分:0)
如果问题是您按日期按字符串排序获得订单。
select distinct convert(varchar, CreatedDate, 101)
from sometable
order by CreatedDate
答案 3 :(得分:0)
为列创建别名,使用别名来排序。
选择
distinct(convert(varchar,CreatedDate,101))为OrderedDate
从某些人
订购OrderedDate
而不是不同,你可以使用group by来实现你想要的。
选择
将(varchar,CreatedDate,101)转换为OrderedDate
从某些人
Group By CreatedDate
按CreatedDate排序
以下代码按预期工作。经过测试。
select
convert(varchar,x.OrderedDate,101)
from
(
select
distinct cast(CreatedDate as date) OrderedDate
from
Test
) x
order by x.OrderedDate