Using Max() function to select group values

谁说胖子不能爱 提交于 2019-11-28 14:44:27

Rank the records with ROW_NUMBER, so that the max value for an sku gets #1. Then keep only those records ranked #1.

select sku, item, value
from
(
  select 
    mytable.*
    row_number() over (partition by sku order by value desc) as rn
  from mytable
)
where rn = 1;

For SKU 1503818 you will get either of these two:

1503818 1636708 0,9440251
1503818 1636709 0,9440251

If you want a particular one (e.g. the one with the higher item number) then add this criteria to Row_Number's ORDER BY clause.

As to the query you tried yourself: You should be looking for sku-value pairs instead:

select SKU, ITEM, VALUE from import
where (sku,value) in (select sku, max(value) from import group by sku);

In case of a tie, as with SKU 1503818, this query will get you both records, however.

Use a common table expression

WITH CTE AS 
(SELECT SKU,ITEM,VALUE,
ROW_NUMBER() OVER (PARTITION BY SKU ORDER BY value DESC)as maxvalue 
FROM import)
SELECT SKU,ITEM,VALUE FROM CTE WHERE maxvalue=1

You can use ... KEEP ( DENSE_RANK ... ) with an aggregation function to get the maximum of a different row:

SELECT SKU,
       MAX( ITEM ) KEEP ( DENSE_RANK LAST ORDER BY VALUE ASC ) AS ITEM,
       MAX( VALUE ) AS VALUE
FROM   IMPORT
GROUP BY SKU;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!