如何使用 MAX 函数过滤 INNER JOIN 的结果
我需要向此查询的结果添加一个带有 MAX 函数的过滤器;
SELECT a.INTEGER_0, a.INTEGER_1, a.DATE_0, a.DATE_1, a.INTEGER_2
FROM TABLE_A a
INNER JOIN
(SELECT b.INTEGER_0, b.INTEGER_1, b.DATE_0, max(b.DATE_1) AS max_date
FROM TABLE_A b
GROUP BY b.INTEGER_0, b.INTEGER_1, b.DATE_0
) AS result
ON a.INTEGER_0 = b.INTEGER_0
AND a.INTEGER_1 = b.INTEGER_1
AND a.DATE_0 = b.DATE_0
AND a.DATE_1 = b.max_date
这没关系!但我需要用 max(INTEGER_2)
过滤结果。
我尝试了另一个 INNER JOIN 但结果很糟糕!
其他信息
行:
1,7,'2011-02-01','2011-01-01',8
1,7,'2011-02-01','2011-01-02',7
1,7,'2011-02-01','2011-01-04',6
1,7,'2011-02-01','2011-01-04',3
1,7,'2011-02-01','2011-01-04',3
正确结果:
1,7,'2011-02-01','2011-01-04',6
I need to add a filter with MAX function to the result of this query;
SELECT a.INTEGER_0, a.INTEGER_1, a.DATE_0, a.DATE_1, a.INTEGER_2
FROM TABLE_A a
INNER JOIN
(SELECT b.INTEGER_0, b.INTEGER_1, b.DATE_0, max(b.DATE_1) AS max_date
FROM TABLE_A b
GROUP BY b.INTEGER_0, b.INTEGER_1, b.DATE_0
) AS result
ON a.INTEGER_0 = b.INTEGER_0
AND a.INTEGER_1 = b.INTEGER_1
AND a.DATE_0 = b.DATE_0
AND a.DATE_1 = b.max_date
This is ok!! But I need to filter the result whit max(INTEGER_2)
.
I tried with another INNER JOIN but the result is bad!
Additional info
Rows:
1,7,'2011-02-01','2011-01-01',8
1,7,'2011-02-01','2011-01-02',7
1,7,'2011-02-01','2011-01-04',6
1,7,'2011-02-01','2011-01-04',3
1,7,'2011-02-01','2011-01-04',3
Correct result:
1,7,'2011-02-01','2011-01-04',6
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
首先,您的查询中有一个语法错误:子查询的别名是
AS result
。您会将其与b
的内部别名混淆。1 行
如果您只需要 一行 具有
max(integer_2)
的行,则ORDER BY
/LIMIT
即可完成此任务。您的查询可能如下所示:所有行
如果您希望结果集中的所有行具有
max(integer_2)
(正如您的查询认为所暗示的那样),那么您可以这样做:或者更好的是,大大简化为:
或者进一步简化
如果性能很重要,请确保在 table_a (date_1, integer_2) 上有一个索引。
First off, you have a syntax error in your query: the alias of the subquery is
AS result
. You confuse that with the inner alias ofb
.1 row
If you want just one row with
max(integer_2)
thenORDER BY
/LIMIT
will do the job. Your query could look like this:All rows
If you want all rows of your result set with
max(integer_2)
(as your query deems to imply) then you could do this:Or better yet, greatly simplify to:
Or simplify some more
Be sure to have an index on table_a (date_1, integer_2) if performance matters.
您尚未指定您使用的 PostgreSQL 版本。如果是 8.4+,您可以尝试不同的方法并使用 排名函数以实现您的目标:
You have not specified which version of PostgreSQL you are using. If it's 8.4+, you could try a different approach and use a ranking function for achieving your goal: