2

I have this table:

CREATE TABLE `table1` (
 `id` INT(11) NOT NULL AUTO_INCREMENT,
 `col1` VARCHAR(30) NULL DEFAULT NULL,
 `col2` VARCHAR(30) NULL DEFAULT NULL,
 `col3` VARCHAR(30) NULL DEFAULT NULL,
 `riskLevel` VARCHAR(30) NULL DEFAULT NULL
 PRIMARY KEY (`id`)
)COLLATE='utf8_general_ci' ENGINE=InnoDB;

What i want to do is group this table by col1, and get the row with the highest riskLevel for each col1 group values.

When using this query:

SELECT id,col1,col2,col3, MAX(riskLevel) 
FROM table1
GROUP BY col1

You get the max riskLevel, but the other values are random, not fittings to the correct row.

I know one solution:

SELECT id,col1,col2,col3, riskLvel
FROM table1 JOIN
(SELECT col1, MAX(riskLevel) as riskLevel
FROM table1
GROUP BY col1) x ON x.col1 = table1.col1 AND x.riskLevel = table1.riskLevel

This solution doesn't seem optimal to me.

Is there another way of getting the described behavior?

Paul White
95.3k30 gold badges439 silver badges689 bronze badges
asked Aug 30, 2016 at 11:07
2
  • 2
    You do need risklevel. This is really a "groupwise max" problem. (That link has more efficient ways to do it.) Commented Aug 30, 2016 at 20:14
  • @Rick James thx rick, the left join is very nice Commented Aug 31, 2016 at 8:11

1 Answer 1

-4
SELECT id,col1,col2,col3, riskLvel
FROM table1
where risklevel IN ( SELECT MAX(riskLevel)
 FROM table1
 GROUP BY col1 )

IF This query is not correct then you can try this query

SELECT id,col1,col2,col3, riskLvel
 FROM table1
 where col1 IN ( SELECT MAX(col1)
 FROM table1
 GROUP BY col1 )
Paul White
95.3k30 gold badges439 silver badges689 bronze badges
answered Feb 17, 2017 at 17:54
2
  • 2
    I don't think this is correct. Commented Feb 17, 2017 at 17:58
  • The second query is not even wrong. Commented Feb 18, 2017 at 20:20

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.