sfg*_*ups 4 sql sql-server-2008
我datetime在表中有一列包含以下数据:
2011-03-23
2011-04-19
2011-04-26
2011-05-26
Run Code Online (Sandbox Code Playgroud)
我想选择mon-yyyy按报告日期降序排序的不同格式输出.我们需要在SQL语句中只选择一列
这个SQL有效,但我想按ReportDate列排序
SELECT distinct SUBSTRING (convert(varchar, ReportDate, 100),1,3) +'-'+
SUBSTRING (convert(varchar, ReportDate, 100),8,4 )
FROM [EnvelopsDB].[dbo].[Envelopes]
Run Code Online (Sandbox Code Playgroud)
产量
Apr-2011
Mar-2011
May-2011
Run Code Online (Sandbox Code Playgroud)
这个SQL给出了一个错误:
SELECT distinct SUBSTRING (convert(varchar, ReportDate, 100),1,3) +'-'+
SUBSTRING (convert(varchar, ReportDate, 100),8,4 )
FROM [EnvelopsDB].[dbo].[Envelopes]
order by ReportDate
Run Code Online (Sandbox Code Playgroud)
错误:
如果指定了SELECT DISTINCT,则消息145,级别15,状态1,行2 ORDER BY项目必须出现在选择列表中.
什么是获得我需要的输出的最佳SQL查询?
with testdata as
(
select cast('2011-03-23' as datetime) as d
union all
select cast('2011-04-19' as datetime)
union all
select cast('2011-04-26' as datetime)
union all
select cast('2011-05-26' as datetime)
)
SELECT DATENAME(month,d)+'-'+DATENAME(year,d)
FROM testdata
GROUP BY DATEPART(year,d), DATEPART(month,d), DATENAME(month,d),DATENAME(year,d)
ORDER BY DATEPART(year,d), DATEPART(month,d)
Run Code Online (Sandbox Code Playgroud)
SELECT DATENAME(month,ReportDate)+'-'+DATENAME(year,ReportDate)
FROM [EnvelopsDB].[dbo].[Envelopes]
GROUP BY DATEPART(year,ReportDate), DATEPART(month,ReportDate), DATENAME(month,ReportDate),DATENAME(year,ReportDate)
ORDER BY DATEPART(year,ReportDate), DATEPART(month,ReportDate)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9441 次 |
| 最近记录: |