Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GROUP BY ignoring an attribute

for example I have this table:

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

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) which 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.

like image 422
Pew Avatar asked Mar 19 '11 19:03

Pew


People also ask

How do I exclude a column from a GROUP BY?

To exclude column from GROUP BY clause we can use Analytical function. In the above example, we have used multiple group functions on multiple combinations of columns.

Does GROUP BY ignore NULL values?

Group functions ignore the NULL values in the column. To enforce the group functions ti include the NULL value, use NVL function.

Can you GROUP BY a column that is not selected?

No, you can GROUP BY a column that was not included in the SELECT statement. For example, this query does not list the price column in the SELECT , but it does group the data by that column.

Does GROUP BY ignore NULL values SQL?

In SQL Server, All Group functions ignore NULL values. For example: the average salary is calculated based on the rows in the table where a valid value is stored (the total salary divided by the number of employees receiving a salary).


2 Answers

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
like image 81
Stephen Perelson Avatar answered Oct 11 '22 12:10

Stephen Perelson


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.

like image 21
Brian Roach Avatar answered Oct 11 '22 10:10

Brian Roach