Reputation: 113
This is a followup question to the excellent answer:
SQL Select only rows with Max Value on a Column
SQLFiddle http://sqlfiddle.com/#!2/3077f/2
Table "yourtable":
| id | val | ignore | content |
-------------------------------
| 1 | 10 | 0 | A |
| 1 | 20 | 0 | B |
| 1 | 30 | 1 | C |
| 2 | 40 | 0 | D |
| 2 | 50 | 0 | E |
| 2 | 60 | 1 | F |
When looking for max val per id, following sql is used:
select yt1.*
from yourtable yt1
left outer join yourtable yt2
on (yt1.id = yt2.id and yt1.val < yt2.val )
where yt2.id is null;
So the result will be in this case
| id | val | ignore | content |
-------------------------------
| 1 | 30 | 1 | C |
| 2 | 60 | 1 | F |
The Question is how to filter out by column "ignore" when it's =1 so the result will be
| id | val | ignore | content |
-------------------------------
| 1 | 20 | 0 | B |
| 2 | 50 | 0 | E |
Upvotes: 2
Views: 1534
Reputation: 1269973
You need to put the condition both in the subquery and the outer query:
select yt1.*
from yourtable yt1 left outer join
yourtable yt2
on yt1.id = yt2.id and yt1.val < yt2.val and yt2.ignore <> 1
where yt2.id is null and yt1.ignore <> 1;
Upvotes: 3
Reputation: 5669
You can simply add another condition and yt1.ignore <> 1
, as below:
select yt1.*
from yourtable yt1
left outer join yourtable yt2
on (yt1.id = yt2.id and yt1.val < yt2.val )
where yt2.id is null and yt1.ignore <> 1;
Upvotes: 1