Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

sql - Using Max() function to select group values

I've got a table like this:

     SKU    ITEM      VALUE
    1503796 1851920 0,9770637
    1503796 1636691 0,9747891
    1503796 1503781 0,9741025
    1503796 3205763 0,9741025
    1503801 1999745 0,9776622
    1503801 1999723 0,9718825
    1503801 3651241 0,9348839
    1503801 1773569 0,9331309
    1503811 1439825 0,97053134
    1503811 1636684 0,96297866
    1503811 1636671 0,96003973
    1503811 1600553 0,9535771
    1503818 1636708 0,9440251
    1503818 1636709 0,9440251
    1503818 1779789 0,9423958
    1503818 3322310 0,9369579

I need to get output like this (grouped with max value):

SKU      ITEM     VALUE
1503796 1851920 0,9770637
1503801 1999745 0,9776622
1503811 1439825 0,97053134
1503818 1636708 0,9440251

tried to use smth like this:

select SKU, ITEM, VALUE from import
where value=(select max(value) from import )

But it select only one row with max value. How to rewrite query?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...