代码改变世界

sql分组最大值相关

2016-03-02 16:05  hf_sun  阅读(597)  评论(0编辑  收藏  举报

房产表tf_estate_card,利润中心组profit_group_code,资产号main_assets_number,原值original_value

查出每个利润中心组的最大原值及其资产号

partition by方式:

select t.main_assets_number, t.profit_group_code, t.original_value
  from tf_estate_card t,
       (select distinct t.profit_group_code,
                        max(t.original_value) over(partition by t.profit_group_code) as max_original_value
          from tf_estate_card t) tmp
 where t.profit_group_code=tmp.profit_group_code and t.original_value=tmp.max_original_value ;

 

group by 方式:

select t.main_assets_number, t.profit_group_code, t.original_value
  from tf_estate_card t,
       (select distinct t.profit_group_code,
                        max(t.original_value) as max_original_value
          from tf_estate_card t group by t.profit_group_code) tmp
 where t.profit_group_code=tmp.profit_group_code and t.original_value=tmp.max_original_value

 

rank()/dense_rank() over(partition by e.deptno order by e.sal desc)方式:

select tmp.main_assets_number, tmp.profit_group_code, tmp.original_value
  from (select t.main_assets_number,
               t.profit_group_code,
               t.original_value,
               rank() over(partition by t.profit_group_code order by t.original_value desc) rank
          from tf_estate_card t) tmp
 where tmp.rank=1

   over:  在什么条件之上。
partition by e.deptno:  按部门编号划分(分区)。
order by e.sal desc:  按工资从高到低排序(使用rank()/dense_rank() 时,必须要带order by否则非法)
rank()/dense_rank():  分级,rank():  跳跃排序,如果有两个第一级时,接下来就是第三级;dense_rank():  连续排序,如果有两个第一级时,接下来仍然是第二级。