有个字段,为定长数字类型,如30.3,其实是表示30个成人3个儿童
    现在Select时,要算出实际有多少人,30.3转为33,10.15转为25,其实就是前后两个相加。当然,也可能出现30这样的数字,后面不跟小数。
    这样的Select语句要怎么写?而且只能通过一条Select语句选择。
    千万别问我为什么数据库要这样设计,已经成这样了,我也没办法。

解决方案 »

  1.   

    select
      case when charindex('.',col)=0 then parsename(col,1) else cast(col as int) end+
      case when charindex('.',col)>0 then right(col,len(col)-charindex('.',col)) else 0 end
    from
      tb
      

  2.   

    --10.15=15+right(10.15,2)
    --30.3=30+right(30.3,1)
    select cast (10.15 as int)+cast(right(ltrim(10.15),len(ltrim(10.15))-charindex('.',ltrim(10.15))) as int)
      

  3.   

    最多就一个点号把?
    use tempdb;
    /*
    create table C
    (
    content nvarchar(10) not null
    );
    insert into C(content)
    values
    ('30.3'),('10.15'),('30');
    */
    select 
    case 
    when CHARINDEX('.',content,0) > 0 
    then CAST(PARSENAME(content,1) AS int) + CAST(PARSENAME(content,2) AS int)
    else content 
    end as [人数]
    from C;
      

  4.   


    select 
    case 
        when CHARINDEX('.',content,0) > 0 
        then CONVERT(INT,PARSENAME(content,1)) + CONVERT(INT,PARSENAME(content,2))
        else content 
    end as [人数]
    from TableName
      

  5.   


    create table #tb(id int,人数 float)
    insert #tb
    select 1,30.15 union all
    select 2,51.2 union all
    select 3,30 union all
    select 4,31.4 union all
    select 5,47.2 union all
    select 6,10 union all
    select 7,22 declare @sql as nvarchar(max)
    set @sql=''
    select @sql=@sql+' union all select '+Ltrim(id) +' as id, '+replace(Ltrim(人数),'.','+')+' as 人数' from  #tb
    set @sql=stuff(@sql,1,10,'')
    exec(@sql)--这样也OK:
    select id,case charindex('.',Ltrim(人数)) when 0 then 人数 else cast(left(Ltrim(人数),charindex('.',Ltrim(人数))-1) as int) end+
    case charindex('.',Ltrim(人数)) when 0 then 0 else cast(substring(Ltrim(人数),charindex('.',Ltrim(人数))+1,len(Ltrim(人数))) as int) end as 人数
    from #tb