admin

SQL仅选择按列过滤的列中具有最大值的行

sql

这是一个很好的答案的后续问题:
SQL仅选择列上具有最大值的行

SQLFiddle http://sqlfiddle.com/#!2/3077f/2

表“您的表”:

| 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     |

当查找每个id的最大val时,使用以下sql:

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;

因此结果将是这种情况

| id | val | ignore | content |
-------------------------------
| 1  | 30  |   1    |   C     |
| 2  | 60  |   1    |   F     |

问题是 当它为= 1时如何按列“ ignore”过滤掉,因此结果将是

| id | val | ignore | content |
-------------------------------
| 1  | 20  |   0    |   B     |
| 2  | 50  |   0    |   E     |

阅读 123

收藏
2021-06-07

共1个答案

admin

您需要将条件同时放在子查询和外部查询中:

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;
2021-06-07