比如: 5分20秒
       7分 40秒
       10分5秒
如何求其和?  ~

解决方案 »

  1.   

    --创建测试数据
    create table tb(col varchar(20))
    insert into tb values('5分20秒')
    insert into tb values('7分40秒')
    insert into tb values('10分5秒')
    select cast(left(col , charindex('分',col) - 1) as int) * 60 + 
           cast(substring(col , charindex('分',col) + 1 , charindex('秒',col) - charindex('分',col) - 1) as int) as 秒
    from tb
    drop table tb/*
    秒           
    ----------- 
    320
    460
    605
    */
      

  2.   

    --创建测试数据
    create table tb(col varchar(20))
    insert into tb values('5分20秒')
    insert into tb values('7分40秒')
    insert into tb values('10分5秒')
    select sum(cast(left(col , charindex('分',col) - 1) as int) * 60 + 
           cast(substring(col , charindex('分',col) + 1 , charindex('秒',col) - charindex('分',col) - 1) as int)) as 秒的总数
    from tb
    drop table tb/*
    秒的总数        
    ----------- 
    1385
    (所影响的行数为 1 行)
    */
      

  3.   

    --创建测试数据
    create table tb(col varchar(20))
    insert into tb values('5分20秒')
    insert into tb values('7分40秒')
    insert into tb values('10分5秒')
    go
    --sql语句
    select col , cast(left(col , charindex('分',col) - 1) as int) * 60 + 
           cast(substring(col , charindex('分',col) + 1 , charindex('秒',col) - charindex('分',col) - 1) as int) 秒 
    from tb
    where charindex('分',col) > 0 and charindex('秒',col) > 0 and charindex('分',col) < charindex('秒',col)
    union all
    select col = '合计', sum(cast(left(col , charindex('分',col) - 1) as int) * 60 + 
           cast(substring(col , charindex('分',col) + 1 , charindex('秒',col) - charindex('分',col) - 1) as int)) as 秒 
    from tb
    where charindex('分',col) > 0 and charindex('秒',col) > 0 and charindex('分',col) < charindex('秒',col)
    --删除表
    drop table tb--结果
    /*
    col                  秒           
    -------------------- ----------- 
    5分20秒              320
    7分40秒              460
    10分5秒              605
    合计                 1385
    (所影响的行数为 4 行)
    */