有一個資料表T1如下,
若用
select t1.name,t1.position,max(t1.price) from t1 group by t1.name,t1.position
好像不會得到如下的結果,
到底要怎麼寫才會將我不想grouping 的欄位,不會grouping呢?
T1:                          name   position   price
--------------------------
gtt    a           50
ddc    b           20
adc    d           10
rfg    f            5
gtt    a           10
adc    g           20
gtt    h           20
欲得到的結果:name   position   max(price)
-------------------------
gtt     a          50
ddc     b          20
adc     g          20

解决方案 »

  1.   

    select name, position,price from (select t1.name,t1.position,t1.price, row_number() over(partition by name order by price desc) rn from t1) where rn = 1;row_number() over(..)
    以name分组,按照price desc排序,取序号为1的记录
      

  2.   

    括号内的就是子查询啊,在子查询里面按照price编号,在外层直接查出可以查查row_number over两个函数的作用。
      

  3.   

    再写一种
    select distinct * from t1 a where not exists(
      select 1 from t1 
        where name=a.name
          and position=a.position
          and price>a.price)
      

  4.   


    赞同。选前两个也可以用这个 把rn=1 改成 rn<=2即可
      

  5.   

    select * from t1 a 
      where (select count(1) from t1 
        where name=a.name
          and position=a.position
          and price>a.price)<=1
      

  6.   

    select distinct t1.name,t1.position,max(t1.price) from t1 group by t1.name,t1.position