How to get MAX int but exclude specific int?
-
30-05-2021 - |
Frage
I'd like to get the max integer from a specific column excluding a value that will always be the max if present. Data may look like the following:
score, empid
1 3
3 3
10 3
1 5
2 5
1 8
2 8
3 8
10 8
In the above, I'd like MAX score less than 10. MAX(score) doesn't work in this case since it will bring back 10. Results should look like this:
score, empid
3 3
2 5
3 8
Any suggestions?
Lösung
select max(score) , empid
from table
where score < (select max(score) from table )
group by empid
Andere Tipps
Here's an alternative method:
SELECT
MAX(CASE WHEN score = 10 THEN NULL ELSE score END) AS [max_score],
empid
FROM
table
GROUP BY
empid
This may be preferable if you prefer to avoid the sub-select.
Following Ben English's answer, if you are excluding only 1 value, you can also use NULLIF for less typing.
SELECT MAX(NULLIF(score, 10)), ...
FROM ...
GROUP BY ...
With CASE WHEN
it's possible to exclude a range of values. Here we exclude all scores more than 10:
SELECT MAX(CASE WHEN score > 10 THEN NULL ELSE score), ...
FROM ...
GROUP BY ...
And here is the IIF
version for less typing:
SELECT MAX(IIF(score > 10, NULL, score)), ...
FROM ...
GROUP BY ...
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow