有一张表里有这样的字段,id,type,price三列
type表示物品类别,price表示价格
假设现在表中有type分别为1和2的数据若干条
如果写出一个SQL语句,同时查询出type为1的最高价格的数据和type为2的最高价格的数据.

解决方案 »

  1.   

    select max(case when type = 1 then price else 0 end),max(case when type = 2 then price else 0 end)
    from ta
      

  2.   

    select
     max(case type when  1 then price else 0 end),
     max(case type when 2 then price else 0 end)
    from
     tb
      

  3.   

    --如果只查type和最大的price
    select type , max(price) max_price from tb where type = 1 or type = 2 group by type--如果查整条记录
    select t.* from tb t where (type = 1 or type = 2) and price = (select max(price) from tb where (type = 1 or type = 2) and type = t.type)
    select t.* from tb t where (type = 1 or type = 2) and not exists (select 1 from tb where (type = 1 or type = 2) and type = t.type and price > t.price)