第一个表 table1 为消费都用的时间:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Table1]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Table1]
GO
CREATE TABLE [dbo].[Table1] (
[AutoID] [int] NOT NULL ,
[BeginTime] [datetime] NULL ,
[EndTime] [datetime] NULL
) ON [PRIMARY]
GO
insert into table1
select 1 ,'2013-10-01 13:04:05.000','2013-10-01 14:04:05.000'
第二张表为记费规则表:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Table2]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[Table2]
GO
CREATE TABLE [dbo].[Table2] (
[AutoID] [int] NOT NULL ,
[BeginTime] [datetime] NULL ,
[EndTime] [datetime] NULL ,
[Fee] [decimal](18, 0) NULL
) ON [PRIMARY]
GO
insert into table2
select 1,'2013-10-01 12:00:00.000','2013-10-01 13:00:00.000',2 union
select 2,'2013-10-01 13:00:00.000','2013-10-01 14:00:00.000',3 union
select 3,'2013-10-01 14:00:00.000','2013-10-01 15:00:00.000',4
计算的sql 语句如下:
select *,cast(DATEDIFF( Minute, begintime,endTime) as decimal(18,4))/60 * fee as cost from(
select
case when b.begintime < a.begintime and a.begintime < b.endTime then a.beginTIme else b.beginTime end as beginTime,
case when b.begintime < a.endTime and a.endTime < b.endTime then a.endTIme else b.endTIme end as EndTime,
b.fee
from table1 a CROSS join table2 b
where
((a.begintime >b.begintime) and (a.begintime < b.endTime)) or
(b.begintime < a.endTime and a.endTime < b.endTime)) as a
结果如下: