if object_id('tb') is not null
drop table tb
go
create table tb(日期 datetime,名称 varchar(50))
insert into tb select '2007-5-25','a'
insert into tb select '2007-5-26','a'
insert into tb select '2007-5-27','a'
insert into tb select '2007-5-28','a'
insert into tb select '2007-5-29','a'
insert into tb select '2007-5-30','a'
insert into tb select '2007-5-31','a'
insert into tb select '2007-6-1','a'
insert into tb select '2007-6-2','a'create function get_wk(@dt datetime)
returns varchar(50)
as
begin
declare @s varchar(50)
set @s=convert(varchar(10),@dt-(datepart(dw,@dt)+@@datefirst-1)%7+1,120)+'到'
+convert(varchar(10),@dt-(datepart(dw,@dt)+@@datefirst-1)%7+7,120)
return @s
endselect dbo.get_wk(日期) as 日期段,count(1) as 数量
from tb
group by dbo.get_wk(日期)日期段 数量
2007-05-21到2007-05-27 2
2007-05-28到2007-06-03 7

解决方案 »

  1.   

    if object_id('tb') is not null
    drop table tb
    go
    create table tb(日期 datetime,名称 varchar(50))
    insert into tb select '2007-5-25','a'
    insert into tb select '2007-5-26','a'
    insert into tb select '2007-5-27','a'
    insert into tb select '2007-5-28','a'
    insert into tb select '2007-5-29','a'
    insert into tb select '2007-5-30','a'
    insert into tb select '2007-5-31','a'
    insert into tb select '2007-6-1','a'
    insert into tb select '2007-6-2','a'
    go
    if object_id('proc_get_wk') is not null
    drop proc proc_get_wk
    go
    create proc proc_get_wk
    @starttime datetime,
    @endtime datetime,
    @type int
    as
    begin
    --周
    if @type=1
    select convert(varchar(10),日期-(datepart(dw,日期)+@@datefirst-1)%7+1,120)+'到'+convert(varchar(10),日期-(datepart(dw,日期)+@@datefirst-1)%7+7,120) as '周',count(1) as '行数'
    from tb 
    where 日期 between @starttime and @endtime
    group by convert(varchar(10),日期-(datepart(dw,日期)+@@datefirst-1)%7+1,120)+'到'+convert(varchar(10),日期-(datepart(dw,日期)+@@datefirst-1)%7+7,120)
    --日
    if @type=2
    select convert(varchar(10),日期,120) as '日',count(1) as '行数' from tb where 日期 between @starttime and @endtime group by convert(varchar(10),日期,120)
    --月
    if @type=3
    select convert(varchar(7),日期,120) as '月',count(1) as '行数' from tb where 日期 between @starttime and @endtime group by convert(varchar(7),日期,120)
    --年
    if @type=4
    select convert(varchar(4),日期,120) as '年',count(1) as '行数' from tb where 日期 between @starttime and @endtime group by convert(varchar(4),日期,120)
    end
    go
    exec proc_get_wk '2007-05-01','2007-05-31',1
    --周 行数
    --2007-05-21到2007-05-27 2
    --2007-05-28到2007-06-03 5
    exec proc_get_wk '2007-05-01','2007-05-31',2
    --日 行数
    --2007-05-25 1
    --2007-05-26 1
    --2007-05-27 1
    --2007-05-28 1
    --2007-05-29 1
    --2007-05-30 1
    --2007-05-31 1
    exec proc_get_wk '2007-05-01','2007-05-31',3
    --月 行数
    --2007-05 7
    exec proc_get_wk '2007-05-01','2007-05-31',4
    --年 行数
    --2007 7