原表结构是这样的:
客户编号 类型 LPG05 LPG10 LPG15
01       5   10    0       0
01      10   0     12      0
01      15   0     0       20
02      5    8     0       0
02      15   0     0       18
每行对应的(同一客户编号,对应的如LPG05,LPG10,LPG15中只会有一列有数值,其余为0,类型如为15,则对应的lpg15字段上一定有值)
经过一查询后,形成这样的表结构
客户编号 类型 数量
01        5  10
01       10  12
01       15  20

要求不要用联合查询方式,谢谢指点。

解决方案 »

  1.   

    --> liangCK小梁 于2008-09-17
    --> 生成测试数据: #T
    if object_id('tempdb.dbo.#T') is not null drop table #T
    create table #T (客户编号 varchar(2),类型 int,LPG05 int,LPG10 int,LPG15 int)
    insert into #T
    select '01',5,10,0,0 union all
    select '01',10,0,12,0 union all
    select '01',15,0,0,20 union all
    select '02',5,8,0,0 union all
    select '02',15,0,0,18--SQL查询如下:select 客户编号,类型,
           数量=coalesce(nullif(LPG05,0),nullif(LPG10,0),nullif(LPG15,0))
    from #T/*
    客户编号 类型          数量
    ---- ----------- -----------
    01   5           10
    01   10          12
    01   15          20
    02   5           8
    02   15          18(5 行受影响)
    */
      

  2.   


    因为用的是access数据库,好像没有coalesce函数
      

  3.   

    select 客户编号 , 类型 , 
      case when LPG05 > 0 then LPG05
           when LPG10 > 0 then LPG10
           when LPG15 > 0 then LPG10
      end as 数量
    from tb
      

  4.   

    select 客户编号,类型,
          iif((LPG05<>0),LPG05,iif(LPG10<>0,LPG10,LPG15)) as 数量
    from #T