日期:2014-05-18 浏览次数:20738 次
create table tb ( [type] varchar(10), startdate datetime, enddate datetime, counttime decimal(5,1), id int identity(1,1) ) insert into tb select '1', '2012-04-18 14:33:22.640', '2012-04-21 14:33:22.640', 3.0 union all select '1', '2012-04-14 14:34:48.970', '2012-04-17 14:34:48.970', 3.0 union all select '2', '2012-04-19 14:34:49.407', '2012-04-21 14:34:49.407', 2.0 union all select '2', '2012-04-23 14:34:50.220', '2012-04-24 14:34:50.220', 1.0 select t1.加班时间 ,t2.调休时间 ,t1.加班时间 -t2.调休时间 AS 结余数 from (select [type],SUM(counttime) AS 加班时间 from tb where [type]='1' group by [type]) t1, (select [type],SUM(counttime) AS 调休时间 from tb where [type]='2' group by [type]) t2
------解决方案--------------------
--> 测试数据:[test] if object_id('[test]') is not null drop table [test] create table [test]( [type] int, [startdate] datetime, [enddate] datetime, [counttime] numeric(2,1), [id] int ) insert [test] select 1,'2012-04-18 14:33:22.640','2012-04-21 14:33:22.640',3.0,1 union all select 1,'2012-04-14 14:34:48.970','2012-04-17 14:34:48.970',3.0,2 union all select 2,'2012-04-19 14:34:49.407','2012-04-21 14:34:49.407',2.0,3 union all select 2,'2012-04-23 14:34:50.220','2012-04-24 14:34:50.220',1.0,4 select 加班总时数,调休总时数,调休总时数-加班总时数 as 本月结余 from( select SUM(case when [type]=1 then [counttime] else 0 end) as 加班总时数, SUM(case when [type]=2 then [counttime] else 0 end) as 调休总时数 from test)a /* 加班总时数 调休总时数 本月结余 6.0 3.0 -3.0 */