表中有三种类型的价格字段(还有其他字段):a_price,b_price,c_price,都是int型,字段的值都大于等于0,三个字段中一定有两个等于0,另外一个大于0,现要查询表中的一条数据,条件是:a_price,b_price,c_price中值大于0,但又是最小的数据。
比如:a_price,b_price,c_price
        0       0       80
        0       35      0
        60      0       0
        ……   ……     ……
三个字段中大于0的最小的值是35,这样就是查询b_price=35的数据,应该怎么写呢?

解决方案 »

  1.   

    select min(newcol)
    from
    (
    select rtrim(a_price) as newcol
    from tablename
    union all
    select rtrim(b_price)
    from tablename
    union all
    select rtrim(c_price)
    from tablename
    )a
    where newcol>0
      

  2.   

    select min(tbl.a) from 
    (
      select min(a_price) a from table
      union all 
      select min(b_price) a from table
      union all
      select min(c_price) a from table
    ) tbl
      

  3.   

    --那这样,就是长了点select * from tablename
    where
    a_price=
    (
    select min(newcol)
    from
    (
    select rtrim(a_price) as newcol
    from tablename
    union all
    select rtrim(b_price)
    from tablename
    union all
    select rtrim(c_price)
    from tablename
    )a
    where newcol>0
    )
    or
    b_price=
    (
    select min(newcol)
    from
    (
    select rtrim(a_price) as newcol
    from tablename
    union all
    select rtrim(b_price)
    from tablename
    union all
    select rtrim(c_price)
    from tablename
    )a
    where newcol>0
    )
    or
    c_price=
    (
    select min(newcol)
    from
    (
    select rtrim(a_price) as newcol
    from tablename
    union all
    select rtrim(b_price)
    from tablename
    union all
    select rtrim(c_price)
    from tablename
    )a
    where newcol>0
    )
      

  4.   

    --如果用变量替换可以变简单点,如下declare @i int
    select @i=min(newcol)
    from
    (
    select rtrim(a_price) as newcol
    from tablename
    union all
    select rtrim(b_price)
    from tablename
    union all
    select rtrim(c_price)
    from tablename
    )aselect * from tablename
    where
    a_price=@i or
    b_price=@i or
    c_price=@i
      

  5.   

    用了上上楼的语句,运行后出现了:“不允许从数据类型money到varchar的隐性转化”,是哪里出了问题呢?
      

  6.   

    --测试的时候用的是int,当时在考虑别的方案,用了rtrim的隐性转换功能,trydeclare @i money
    select @i=min(newcol)
    from
    (
    select a_price as newcol
    from tablename
    union all
    select b_price
    from tablename
    union all
    select c_price
    from tablename
    )a
    where newcol>0select * from tablename
    where
    a_price=@i or
    b_price=@i or
    c_price=@i
      

  7.   

     
    declare @a table (a int, b int, c int)insert @a 
    select 
    0,       0,       80 union all select 
    0,       35,      0  union all select
    60,      0,       0
     
    select a+b+c as a into #aaa from @aselect * from #aaaselect * from #aaa x where not exists (select 1 from #aaa where a<x.a)drop table #aaa