繁体   English   中英

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

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

这是优秀答案的后续问题:
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 时过滤掉它,因此结果将是

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

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

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;

您可以简单地添加另一个条件and yt1.ignore <> 1 ,如下所示:

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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM