zoukankan      html  css  js  c++  java
  • 按时间分段算费用

    第一个表 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

    结果如下:

  • 相关阅读:
    js对象与字符串相互转换
    11 ~ express ~ 解决 cookie 中文报错的问题
    10 ~ express ~ 使用 cookie 保存用户 信息
    href="javacript:;" href="javacript:void(0);" href="#"区别。。。
    9 ~ express ~ 用户注册
    8 ~ express ~ 基于数据库的验证
    SpringBoot整合RocketMQ
    RabbitMQ(五)消息发送失败后的处理
    分享一些JVM常见的面试题(转)
    双亲委派模型
  • 原文地址:https://www.cnblogs.com/xiajing12345/p/3383758.html
Copyright © 2011-2022 走看看