Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get max value of non duplicated records

Is it possible this?
I have the following table:

Col1 Col2 col3
code1 US 9
code1 0 5
code2 US 4
code2 0 11
code3 0 11

and I’m trying to get the higher col3 value filtering by col1 and col2 my attempt right now is:

SELECT MAX(col3), col2, col1, count(col1) FROM `mytable` WHERE (col1 IN ('code1', 'code2') ) AND ((col2 = 'US') OR (col2 = '0')) GROUP BY col1;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

and my result:

Col1 Col2 col3 count(col1)
code1 US 9 2
code2 0 11 2

But what I need is if both codes have a col2 with value equal to ‘US’ then return the higher col3 value from those and ignore the ones with ‘0’ or if one of those codes only have one row with col2 equal to ‘0’ then compare between the code1 = ‘US’ and the code2 = ‘0’ giving the result:

Col1 Col2 col3 count(col1)
code2 0 11 2

Is it possible to achieve this with a mysql query? or should I use php?

Thank you in advance.

>Solution :

You have very specific where clause, so you need to repeat them in teh subselect as in the Main Select

SELECT * FROM tab1 WHERE col3 = 
(SELECT MAX(col3) FROM tab1  WHERE (col1 IN ('code1', 'code2') ) AND ((col2 = 'US') OR (col2 = '0')))
AND (col1 IN ('code1', 'code2') ) AND ((col2 = 'US') OR (col2 = '0'))
ORDER BY col1
LIMIT 1
Col1  | Col2 | col3
:---- | :--- | ---:
code2 | 0    |   11

db<>fiddle here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading