使用SQL Server 2000
表1
ID Salary (Monthly) perday (salary)
001 3000 100
002 1500 50
003 4500 150
Salary
,perday
列的数据类型为float
表2
ID Date Latetime (HH:mm)
001 01/02/2012 00:15
001 02/02/2012 00:10
001 03/02/2012 00:45
001 04/02/2012 00:29
001 05/02/2012 01:00
002 11/03/2012 00:02
002 12/03/2012 00:20
002 13/03/2012 00:29
002 14/03/2012 01:00
002 10/03/2012 01:30
002 10/03/2012 02:00
我想根据晚上的数量扣除工资额。
条件
01至29分钟的晚期情况
30分钟至1小时的晚期病情
table2的预期输出
4th onwards
ID Ist 2nd 3rd days Amount Deducted
001 0 10 50 2 250 310
002 0 10 10 1 100 120
输出说明
用户001迟到5次作为计数(晚期)来自table2
如何为上述条件创建查询?
答案 0 :(得分:3)
--create and populate penalty rules
create table table4( latetype int null, nthtime int null, mulfactor float null)
insert into table4 values (1,1,0) insert into table4 values (1,2,0.1)
insert into table4 values (1,3,0.25) insert into table4 values (1,4,0.5)
insert into table4 values (2,1,0) insert into table4 values (2,2,0.5)
insert into table4 values (2,3,1.0) insert into table4 values (2,4,1.5)
--create third table to populate the nthtime and latetype for table2
select x.id, date,
(select count(*) from table2 where id=x.id and date<=x.date) as nthtime,
case when x.latetime<'00:30' then 1 else 2 end as latetype
into table3
from table2 x join table1 on table1.id = x.id
--select the deduction amounth per id
select table1.id,
sum(table1.perday*
isnull(mulfactor, case when latetype = 1 then .5 else 1.5 end) )as deduction
from table3 a
left join table4 b on a.latetype=b.latetype and a.nthtime=b.nthtime
join table1 on table3.id = table1.id
group by table1.id