如何获得每个月的第一个和最后一个

时间:2016-11-11 03:31:50

标签: sql sql-server tsql

如何为一个月的1到10个日期添加第一个,并在一个月的20到30天添加最后一个。

DECLARE @Today DATE = '2016-11-05'

Select  CONVERT(VARCHAR(5),datepart (DW, @Today)-1 )+' DAYS of '+ LEFT(DATENAME(month,@Today),3) Comments

我变得像这样

Comments
6 DAYS of Nov

如何得到这样:

Comments
First 6 DAYS of Nov

如果我将日期定为'2016-11-24'

需要这样的输出

     Comments
     Last 4 DAYS of Nov

建议我继续进行的方式

4 个答案:

答案 0 :(得分:4)

使用case声明:

Select (CASE WHEN day(@today) <= 10 THEN 'First '
             WHEN day(@today) >= 20 THEN 'Last '
             ELSE ''
        END) + CONVERT(VARCHAR(5), datepart(DW, @Today)-1 ) + ' DAYS of ' +
        LEFT(DATENAME(month, @Today), 3) as Comments

编辑:

哦,现在我看到原始查询不对。所以你想要更像这样的东西:

Select (CASE WHEN day(@today) <= 10 THEN 'First ' + DATENAME(day, @today) + ' DAYS of ' + LEFT(DATENAME(month, @Today), 3)
             WHEN day(@today) >= 20 AND MONTH(@Today) IN (1, 3, 5, 7, 8, 10, 12) THEN 'Last ' + CAST(31 - day(@today) as varchar(255))
             WHEN day(@today) >= 20 AND MONTH(@Today) IN (4, 6, 9, 11) THEN 'Last ' + CAST(30 - day(@today) as varchar(255))
             WHEN day(@today) >= 20 AND MONTH(@Today) IN (2) AND YEAR(@Today) % 4 = 0 THEN 'Last ' + CAST(29 - day(@today) as varchar(255))
             WHEN day(@today) >= 20 AND MONTH(@Today) IN (2) AND YEAR(@Today) % 4 <> 0 THEN 'Last ' + CAST(29 - day(@today) as varchar(255))
             ELSE CAST(day(@today) as varchar(255))
        END)  + ' DAYS of ' + LEFT(DATENAME(month, @Today), 3) as Comments

答案 1 :(得分:0)

DECLARE @Today DATE = '2016-11-09'

Select (CASE WHEN day(@today) <= 10 THEN 'First ' + DATENAME(day, @today)
             WHEN day(@today) >= 20 THEN 'Last ' + CAST(DAY(DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,@Today)+1,0))) - day(@today) as varchar(255))
             ELSE CAST(day(@today) as varchar(255) )
        END)  + ' DAYS of ' + LEFT(DATENAME(month, @Today), 3) 

答案 2 :(得分:0)

使用SQL Server 2012,开发人员现在可以使用新的SQL日期函数EOMonth()来计算给定日期所在月份的最后日期。

这是我的查询

--DECLARE @Today DATE = '2016-11-05'
DECLARE @Today DATE = '2016-11-24'

SELECT
 case when DATEPART(dd,@Today) <= 10 then
 'First ' + convert(varchar(2), DATEPART(dd,@Today)) + ' of ' + DATENAME(mm,@Today)
 else
 'Last ' + convert(varchar(2), DATEDIFF(dd, @Today, EOMONTH (@Today))) + ' of ' + DATENAME(mm,@Today)
 end

SQL EOMonth() function可以更轻松地计算一个月的最后日期,也可以间接计算下个月或上个月的第一个日期

答案 3 :(得分:0)

SELECT case when DATEPART(dd,@Today) <= 10 then
 'First ' + convert(varchar(2), DATEPART(dd,@Today)) + ' DAYS of ' + DATENAME(mm,@Today) 
WHEN DATEPART(dd,@Today) >= 20 then  'Last ' + convert(varchar(2),
DATEDIFF(dd, @Today, EOMONTH (@Today))) + ' DAYS of ' + DATENAME(mm,@Today) 
ELSE @Today END