生成指定日期段的日期列表,月份列表

if exists(select * from sys.sysobjects where id = OBJECT_ID(N'[dbo].[f_getdate]') and xtype in (N'FN',N'IF',N'TF'))
drop function [dbo].[f_getdate]
go
/*--生成列表
生成指定日期段的日期列表


--查询工作日
SELECT * FROM dbo.f_getdate('2005-1-3','2005-4-5',0)

--查询休息日
SELECT * FROM dbo.f_getdate('2005-1-3','2005-4-5',1)

--查询全部日期
SELECT * FROM dbo.f_getdate('2005-1-3','2005-4-5',NULL)
--*/


create function dbo.f_getdate(
@begin_date datetime,
@end_date datetime,
@bz bit
)returns @re table(id int identity(1,1),Date datetime,Weekday nvarchar(13))
as 
begin
declare @tb table(id int identity(0,1), a bit)
insert into @tb select top 366 0 from sysobjects a,sysobjects b


if @bz = 0
while @begin_date <= @end_date 
begin
insert into @re(Date,Weekday)
select Date,DATENAME(Weekday,Date)
from (
select Date = DATEADD(day,id,@begin_date)
 from @tb
) a where Date <= @end_date and 
(DATEPART(Weekday,Date) + @@DATEFIRST - 1) % 7 between 1 and 5
set @begin_date = DATEADD(day,366,@begin_date)
end
else if @bz = 1
while @begin_date <=@end_date 
begin
insert into @re(Date,Weekday)
select Date,DATENAME(Weekday,Date) from
(
select Date = DATEADD(day,id,@begin_date)
from @tb
) a where Date <= @end_date 
and (DATEPART(Weekday,Date) + @@DATEFIRST - 1) % 7 in (0,6)
set @begin_date = DATEADD(day,366,@begin_date)
end
else
while @begin_date < @end_date 
begin
insert into @re(Date,Weekday)
select Date,DATENAME(Weekday,Date) from
(
select Date = DATEadd(day,id,@begin_date)
from @tb
) a where Date <= @end_date 
set @begin_date = DATEADD(day,366,@begin_date)
end
return
end
go


SELECT * FROM dbo.f_getdate('2012-12-31','2013-12-31',0)

=========================

use sqltest
go
declare @t Table(id int,date datetime,[money] decimal(10,2))
insert into @t select 1,'2005-1-1',10
union all select 2,'2005-2-21',20
union all select 3,'2005-3-1',30
union all select 2,'2005-3-1',40
union all select 3,'2005-5-1',50
union all select 2,'2005-11-21',60
union all select 3,'2005-11-11',70


select a.[MONTH],[money] = ISNULL(b.[money],0)
from (
select [MONTH] = 1 union all
select [MONTH] = 2 union all
select [MONTH] = 3 union all
select [MONTH] = 4 union all
select [MONTH] = 5 union all
select [MONTH] = 6 union all
select [MONTH] = 7 union all
select [MONTH] = 8 union all
select [MONTH] = 9 union all
select [MONTH] = 10 union all
select [MONTH] = 11 union all
select [MONTH] = 12
)a
left join (
select [month]= MONTH(Date),[money]= SUM([money])
from @t group by MONTH(Date) 
) b on a.[month] = b.[month]


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值