简体   繁体   English

如何从 SQL 查询中获得最大结果?

[英]How to get max results from SQL Query?

I have a very simple query and I'm stucked trying to filter only the MAX(b.id):我有一个非常简单的查询,我被困在试图只过滤 MAX(b.id):

SELECT 
A.id,
b.id
from emp A
JOIN ACS B
ON B.id = A.id
and A.id =1553

In table B, we have three lines for the A.ID.在表 B 中,我们有三行 A.ID。 I need to get only the higher one.我只需要得到更高的。 I tried to use "MAX(B.ID)" but it didn't worked.我尝试使用“MAX(B.ID)”,但没有奏效。

These are the results:这些是结果:

[
     {
          "rownumber": 1,
          "A.id": 1553,
          "b.id": 749
     },
     {
          "rownumber": 2,
          "A.id": 1553,
          "b.id": 4356
     },
     {
          "rownumber": 3,
          "A.id": 1553,
          "b.id": 4661
     }
]

I just need to return the MAX(b.ID).我只需要返回 MAX(b.ID)。 In this case, I need only:在这种情况下,我只需要:

     {
          "rownumber": 3,
          "emp_id": 1553,
          "id": 4661
     }

I'll remove the A.id from filter selection and for each line in AI need only the MAX from B.我将从过滤器选择中删除 A.id,对于 AI 中的每一行,只需要 B 中的 MAX。

Thanks in advance!提前致谢!

What is the best way to do it?最好的方法是什么?

A simple approach is to use RANK() .一个简单的方法是使用RANK()

Try this:尝试这个:

select *
from
(
SELECT 
  A.id,
  b.id,
  RANK()OVER(ORDER BY b.ID desc) as rnk
from emp A
JOIN ACS B
  ON B.id = A.id
  and A.id =1553
) as r
where rnk=1

As you only want the id from ACS you can use a correlated subquery由于您只需要来自ACSid ,因此您可以使用相关子查询

select e.id, (select Max(id) from ACS a where a.id = e.id) id
from emp e
where e.id = 1553;

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

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