简体   繁体   English

在给定的间隔内选择年/月格式

[英]Select year/month format in a given interval of years


I am finding a simple solution . 我正在寻找一个简单的解决方案。
I can select months in given interval of years by this- 我可以以此方式在给定的年份间隔中选择月份-

SELECT DISTINCT DATEPART(month, colDate) AS 'Month'    --result=> 4
FROM MyTable
WHERE YEAR(colDate)>='2012'
AND YEAR(colDate)<='2013'


And, I can select years in given interval of years by this- 而且,我可以以此方式在给定的年份间隔中选择年份-

SELECT DISTINCT DATEPART(year, colDate) AS 'Year'      --result=> 2012
FROM MyTable
WHERE YEAR(colDate)>='2012'
AND YEAR(colDate)<='2013'

How can I directly select these result in yyyy/MM format? 如何直接选择yyyy / MM格式的结果? =>2012/04
Is there any way for this problem? 有什么办法解决这个问题吗?
Thanks for your interest and replies. 感谢您的关注和回复。

You should find this approach much nicer in terms of execution plan and potential index usage on the colDate column, if one exists, compared to your current approach (most importantly the where clause). 与当前的方法(最重要的是where子句)相比,您应该在colDate列上的执行计划和潜在索引使用方面发现这种方法更好。

SELECT d = REPLACE(CONVERT(CHAR(7), d, 121), '-', '/')
FROM 
(
  SELECT DISTINCT 
    d = DATEADD(MONTH, DATEDIFF(MONTH, '19000101', colDate), '19000101')
    FROM dbo.MyTable
    WHERE colDate >= '20120101'
    AND colDate < '20140101'
) AS x
ORDER BY d;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM