读书人

急求一汇总SQL语句实现!该如何解决

发布时间: 2012-02-20 21:18:23 作者: rapoo

急求一汇总SQL语句实现!!!!!!!!!
表A
--------------------------
Employee_sn StartDate EndDate
1 '2007-01-02 ' '2007-01-03 '
1 '2007-01-05 ' '2007-01-06 '
1 '2007-01-09 ' '2007-01-13 '
2 '2007-02-02 ' '2007-02-03 '
3 '2007-04-02 ' '2007-04-03 '

表B
---------------------------
Employee_sn CreateDate
1 '2007-01-02 '
1 '2007-01-05 '
1 '2007-01-03 '
3 '2007-01-02 '
1 '2007-01-04 '
1 '2007-01-02 '
2 '2007-01-02 '

表C
--------------------------
Employee_sn StartDate EndDate Count
1 '2007-01-02 ' '2007-01-03 ' 3
1 '2007-01-05 ' '2007-01-06 ' 1
1 '2007-01-09 ' '2007-01-13 ' 0
2 '2007-02-02 ' '2007-02-03 ' 1
3 '2007-04-02 ' '2007-04-03 ' 1
---------------------
就是根据表A中的时间段和员工编号到表B中去统计出对应的员工在该时间段的记录总数.
表A中的员工可能会有多个时间段,但时间段彼此不会重复.
---------
在线等待...

[解决办法]
select Employee_sn,StartDate,EndDate,(select sum(1) from B where B.employee_sn=A.employee_sn and B.createdate between StartDate and EndDate) as Count from A

[解决办法]
drop table A,B
go
create table A(Employee_sn int,StartDate datetime,EndDate datetime)
insert into A
select 1, '2007-01-02 ', '2007-01-03 '
union all select 1, '2007-01-05 ', '2007-01-06 '
union all select 1, '2007-01-09 ', '2007-01-13 '
union all select 2, '2007-02-02 ', '2007-02-03 '
union all select 3, '2007-04-02 ', '2007-04-03 '

create table B(Employee_sn int,CreateDate datetime)
insert into B
select 1, '2007-01-02 '
union all select 1, '2007-01-05 '
union all select 1, '2007-01-03 '
union all select 3, '2007-01-02 '
union all select 1, '2007-01-04 '
union all select 1, '2007-01-02 '
union all select 2, '2007-01-02 '

select *,(select count(*) from B where B.Employee_sn=A.Employee_sn and B.CreateDate between A.StartDate and A.EndDate) as [Count]
from A

/*
Employee_sn StartDate EndDate Count
----------- ------------------------------------------------------ ------------------------------------------------------ -----------
1 2007-01-02 00:00:00.000 2007-01-03 00:00:00.000 3
1 2007-01-05 00:00:00.000 2007-01-06 00:00:00.000 1
1 2007-01-09 00:00:00.000 2007-01-13 00:00:00.000 0
2 2007-02-02 00:00:00.000 2007-02-03 00:00:00.000 0
3 2007-04-02 00:00:00.000 2007-04-03 00:00:00.000 0

(所影响的行数为 5 行)

*/

读书人网 >SQL Server

热点推荐