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

100%难以写出来的slq查寻统计,求助?
有一表记录了工作记录        
sj     司机表        
A司机        
B司机        
C司机        
...        
 
work     司机工作记录表        
A司机     开A车     2007-06-01        
A司机     开B车     2007-06-05        
A司机     开A车     2007-06-12        
B司机     开B车     2007-06-01        
B司机     开A车     2007-06-05        
B司机     开B车     2007-06-12        
C司机     开C车     2007-05-22        
...        
 
Cost     车辆固定费用表        
车     费用类型     交费     交费日期     到期日期        
A车     管理费     100     2007-05-29至     2007-06-08        
A车     保险费     1000     2007-06-01     2008-06-01        
B车     管理费     300     2007-04-22     2007-08-22        
...        
统计司机在2007-06-01至于     2007-06-22日间A司机、B司机...所要分担的费用        
车辆固定费用要求分别分分摊到每个司机开车的区间的每一天内,请问有高手能设计出此sql语句吗,谢谢?        
查查条件     1开始时间     2结束时间     3司机名        
显示要求        
司机名     费用总和(Cost表中管理费+保险费+...)

------解决方案--------------------
create table Cost
(
car char(2) not null,
Type varchar(20) not null ,
cost money null,
starttime datetime null,
endtime datetime null
)

insert into cost
select 'A ' , 'guanlifei ' ,100, '2007-05-29 ', '2007-06-08 '
union all select 'A ' , 'baoxianfei ' ,1000, '2007-06-01 ', '2008-06-01 '
union all select 'B ' , 'guanlifei ' ,1000, '2007-04-22 ', '2007-08-22 '

create table sj
(sjname char(8) not null)

insert into sj
select 'A '
union all select 'B '
union all select 'C '

create table sjwork
(sjname char(8) not null,
car char(2) not null ,
riqi datetime not null)

insert into sjwork
select 'A ' , 'A ' , '2007-06-01 '
union all select 'A ' , 'B ' , '2007-06-05 '
union all select 'A ', 'A ', '2007-06-12 '
union all select 'B ', 'B ' , '2007-06-01 '
union all select 'B ' , 'A ' , '2007-06-05 '
union all select 'B ' , 'B ' , '2007-06-12 '
union all select 'C ' , 'C ', '2007-05-22 '

select datediff (day , starttime,endtime )
from cost

create proc getcost
@starttime datetime,
@endtime datetime,
@sjname char(8)
as
select sjname as '司机名 ' ,
sum(allcost) as '费用总和 '
from (
select cost.car ,
sjname ,
riqi,