695
社区成员
发帖
与我相关
我的任务
分享
--------------------------
-- 模拟原始数据
if object_id('tb') is not null
drop table tb
go
create table tb
(fDate datetime,
fQty int
)
go
insert tb
select '2010-03-02',100 union all
select '2010-03-03',115 union all
select '2010-03-04',116 union all
select '2010-03-05',117 union all
select '2010-03-06',118 union all
select '2010-03-07',119 union all
select '2010-03-08',120 union all
select '2010-03-09',121 union all
select '2010-03-10',122 union all
select '2010-03-11',123 union all
select '2010-03-12',124 union all
select '2010-03-13',125 union all
select '2010-03-14',126 union all
select '2010-03-15',127 union all
select '2010-03-16',128 union all
select '2010-03-17',129 union all
select '2010-03-18',130
go
-- select * from tb
--------------------------
-- 建自定义的周函数
if object_id('fweek') is not null
drop function fweek
go
create FUNCTION fweek
(@FromDate DateTime,@CalaDate datetime)
RETURNS int
AS
begin
declare @fweek int
declare @days int
set @days = datediff(dd,@fromdate,@caladate)
set @fweek = cast(@days / 7 as int) + 1
return @fweek
end
go
--------------------------
-- 数据测试
declare @fromdate datetime
declare @todate datetime
select @fromdate = '2010-03-02',@todate = '2010-03-17'
select
dbo.fweek(@fromdate,fDate) as ffweek,
sum(fQty) as ffTotalQty
from tb
where fDate >= @fromdate and fDate <= @todate
group by dbo.fweek(@fromdate,fDate)
--------------------------
-- 测试结果
/*
(17 row(s) affected)
ffweek ffTotalQty
----------- -----------
1 805
2 868
3 257
(3 row(s) affected)
*/
不懂,帮顶,学习,蹭分.