GROUP BY ignoring an attribute

大憨熊 提交于 2019-12-06 21:33:45

问题


for example i have this table:

itemgroup | description | price
A, a, 10
A, b, 12
A, c, 14
B, g, 11
B, h, 16

now i want to select the rows with the highest price in one group like this:

A, c, 14
B, h, 16

The SQL query (is fully functional) wich gets me near this is:

SELECT itemgroup, MAX( price ) 
FROM table
GROUP BY itemgroup

A, 14
B, 16

By trying this I get an "not a GROUP BY expression"-error:

SELECT itemgroup, description, MAX( price ) 
FROM table
GROUP BY itemgroup

I need something like this pseudo query:

SELECT itemgroup, IGNORE( description), MAX( price ) 
FROM table
GROUP BY itemgroup

I hope i could explain my little problem.


回答1:


I normally end up doing something like:

SELECT t1.itemgroup, t1.description, t1.price
FROM table t1, 
    (SELECT itemgroup, MAX( price ) as price
     FROM table
     GROUP BY itemgroup) t2
WHERE t1.itemgroup = t2.itemgroup
AND t1.price = t2.price



回答2:


Use the analytic functions:

SELECT itemgroup, description, price FROM 
    (select itemgroup, description, price, RANK() 
    OVER (PARTITION BY itemgroup ORDER BY max(price) DESC) as rank 
    FROM  group by itemgroup,description,price)a 
WHERE a.rank = 1
ORDER BY itemgroup;

There's a lot of power in the analytic functions - learning them can help you in a lot of situations.



来源:https://stackoverflow.com/questions/5364429/group-by-ignoring-an-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!