参考下面语句,不同的数据库可能日期处理函数不一样。
set datefirst 1 ;-- 设置周1为第一天
DECLARE @wyr varchar(100) -- 控件名称
set @wyr='日'
--set @wyr='周'
--set @wyr='月'
select *,case when @wyr='日' or len(@wyr)=0 then CONVERT(varchar(100),ddate,23)
when @wyr='周' then 周区间
when @wyr='月' then cast(month(ddate) as varchar(100))
else CONVERT(varchar(100),ddate,23) end as 横向扩展字段
from (
select ddate,
'第'+cast((datepart(wk,ddate) - datepart(wk,convert(varchar(7),ddate,120) + '-01') + 1) as varchar(2)) + '周' AS 周,
case when month(ddate) >
month(DATEADD(WEEK, DATEDIFF(WEEK,0,CONVERT(DATETIME,ddate,120)-1),0))
then convert(varchar(10),DATEADD(DD,-DATEPART(day,ddate)+1,ddate),120)
else convert(varchar(10),DATEADD(WEEK, DATEDIFF(WEEK,0,CONVERT(DATETIME,ddate,120)-1),0),120)
end -- AS 周首日期,
+'=>'+
case when month(ddate) <
month(DATEADD(DAY,6,DATEADD(WEEK, DATEDIFF(WEEK,0,CONVERT(DATETIME,ddate,120)-1),0)))
then convert(varchar(10),dateadd(dd,-DatePart(day,dateadd(MM,1,ddate)),dateadd(MM,1,ddate)),120)
else convert(varchar(10),DATEADD(DAY,6,DATEADD(WEEK, DATEDIFF(WEEK,0,CONVERT(DATETIME,ddate,120)-1),0)),120)
end -- AS 周未日期,
AS 周区间
from (
select dateadd(dd,number,cast('2024'+'-01-01' as datetime)) ddate
from master..spt_values
where [type] = 'p' and number between 0 and 400
) d
where d.ddate>='2024-09-01' and d.ddate<='2024-09-30' -- 时间区间控件
group by ddate
) ss