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

SQL count or max (sqlite)

The table is like this:

ratio|user
  0.1|2
  0.3|2
  1  |2
  1  |2
  0.4|3
  0.7|3

The query should return, for each user, either the number of times the ratio is 1, or, if there is no 1 ratio for that user, the highest ratio. So given the table above, the query should return:

2|2
3|0.7

because there are two "1" values for ratio for user 2, and the highest ratio for user 3 is 0.7.

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

What I have for now is select user,count(ratio) from table where ratio = 1 group by user; but obviously that fails at the second part of the requirement. Should I make a sub-table already populated with the result of that first query…?

>Solution :

Use a CASE expression to choose between the count and the highest value:

SELECT user, CASE WHEN SUM(ratio = 1) > 0
                  THEN SUM(ratio = 1) ELSE MAX(ratio) END AS ratio
FROM yourTable
GROUP BY user;
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