日期:2014-05-18  浏览次数:20555 次

存儲過程查詢10年內 每個月的在職人數
我現在遇到一個問題~
就是在一個資料表里查詢 出每個月的 人數,表里字段只有每個人進來的日期和離開的日期~
我需要查詢10年內 每個月有多少人在職~
有沒有循環判斷 每個月的開始和結束日期的方法~

以下是手工寫的一個月查詢的語句
Declare @stadate datetime
Declare @enddate datetime
set @stadate = '1998-01-01'
set @enddate = '1998-01-31'
select * from empc where (hold_date <@stadate or (hold_date >=@stadate and hold_date <=@enddate)) and (dimission_date is null or (dimission_date >=@stadate and dimission_date <=@enddate) or dimission_date >@enddate)

現在需要查詢10年內每個月的人數~
請前輩們指點一下~
先謝過~



------解决方案--------------------
按年月循环,每年每个月份统计一次,把数据追加到临时表中。

------解决方案--------------------


可以不用考虑一个人连续在线超过一个月的情况,那么这样不就可以了吗!

select * from empc where datediff(month,hold_date,@stadate)=0 or datediff(month,dimission_date,@enddate)=0


------解决方案--------------------
create Table T(id int,be datetime, en datetime)
insert into T
select 1 ,'2007-1-1','2007-10-5' union all
select 2 ,'2007-3-1','2007-10-5' union all
select 3 ,'2007-3-1','2007-9-5' union all
select 4 ,'2007-5-1','2007-8-5'

GO
--120個月即10年
select top 120 tmp=identity(int,0,1) into # from syscolumns a,syscolumns b

--如某月的人數為0也要顯示,可用# left T的方式
select convert(char(06),dateadd(month,tmp, be),112) as [monthly] ,count(*) as num from T
inner join #
on datediff(month,be,en)>=#.tmp
group by convert(char(06),dateadd(month,tmp, be),112)

/*
monthly num
------- ----------- 
200701 1
200702 1
200703 3
200704 3
200705 4
200706 4
200707 4
200708 4
200709 3
200710 2
*/

drop table T,#