FQTXX varchar(6000) --其他信息 格式:(篮号:12,34,56)
    --前重:52|后重:34|减重:18|平均反射率:1我要把  前重 后重 减重 平均反射率  都分别取出来作为一个新的字段显示
有些值是空的
要先判断值是否为空,再判断值里是否有‘减重。’因为这个字段里保存了很多其他的信息求解要怎么写

解决方案 »

  1.   


    --> 测试数据:[test]
    if object_id('[test]') is not null 
    drop table [test]
    create table [test](
    [FQTXX] varchar(38)
    )
    insert [test]
    select '前重:10.76|后重:10.32' union all
    select '前重:10.39|后重:9.93' union all
    select '前重:11.12|后重:10.67|平均反射率:22.77' union all
    select '前重:10.50|后重:10.07' union all
    select '前重:10.98|后重:10.53' union all
    select '前重:10.99|后重:10.55' union all
    select '前重:10.39|后重:9.92' union all
    select '前重:10.30|后重:9.85|平均反射率:23.43' union all
    select '前重:10.58|后重:10.18' union all
    select '' union all
    select '' union all
    select '前重:11.09|后重:10.64'
    goalter table test add id int identity(1,1)
    go
    with T (id,P1,P2) as
    (
        select id,charindex('|','|'+[FQTXX]),charindex('|',[FQTXX]+'|')+1 from [test]
        union all
        select a.id,b.P2,charindex('|',[FQTXX]+'|',b.P2)+1 
        from [test] a join T b 
        on a.id=b.id 
        where charindex('|',[FQTXX]+'|',b.P2)>0
    ),m
    as(
    select a.id,[FQTXX]=substring(a.[FQTXX]+'|',b.P1,b.P2 - b.P1 - 1) 
    from [test] a join T b 
    on a.id=b.id 
    ),n
    as(
    select id,
    left([FQTXX],
    case when CHARINDEX(':',[FQTXX])-1<0 then 0 else CHARINDEX(':',[FQTXX])-1 end) [FQTXX],
    RIGHT([FQTXX],LEN([FQTXX])-CHARINDEX(':',[FQTXX])) as value
    from m
    )
    select 
    前重,后重,前重-后重 as '减重',
    平均反射率
    from(
    select id,
    max(case when [FQTXX]='前重' then cast(value as decimal(5,2)) else 0 end) '前重',
    max(case when [FQTXX]='后重' then cast(value as decimal(5,2)) else 0 end) '后重',
    max(case when [FQTXX]='平均反射率' then cast(value as decimal(5,2)) else 0 end) '平均反射率'
    from n
    group by id
    )lee/*
    前重 后重 减重 平均反射率
    --------------------------------------------------
    10.76 10.32 0.44 0.00
    10.39 9.93 0.46 0.00
    11.12 10.67 0.45 22.77
    10.50 10.07 0.43 0.00
    10.98 10.53 0.45 0.00
    10.99 10.55 0.44 0.00
    10.39 9.92 0.47 0.00
    10.30 9.85 0.45 23.43
    10.58 10.18 0.40 0.00
    0.00 0.00 0.00 0.00
    0.00 0.00 0.00 0.00
    11.09 10.64 0.45 0.00
    */