SQL Select only rows with Max Value on a Column FILTERED by Column

て烟熏妆下的殇ゞ 提交于 2019-12-10 22:58:21

问题


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     |

回答1:


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;



回答2:


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;


来源:https://stackoverflow.com/questions/25245008/sql-select-only-rows-with-max-value-on-a-column-filtered-by-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!