在内部联接中选择不同的值

时间:2018-08-06 14:11:26

标签: sql sql-server

我有以下查询,而我想要的输出将是仅获取具有最高time的每个引脚的行:

SELECT id,pin,time,companyid
  from v20records
  inner join tabuti on v20records.pin = tabuti.altuti 
                   and tabuti.codemp = v20records.companyid 
                   and v20records.companyid = 7

这是我当前的结果:

id          pin     time                    companyid   
124887051   9999    2018-08-06 11:36:22.000 7
124887052   9999    2018-08-06 11:50:57.000 7
124887053   9876    2018-08-06 14:01:27.000 7
124887054   9876    2018-08-06 14:03:14.000 7

这是我想要的结果:

id          pin     time                    companyid   
124887052   9999    2018-08-06 11:50:57.000 7
124887054   9876    2018-08-06 14:03:14.000 7

我尝试使用distinct,并获得每一个的最大时间,但是没有成功。有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

一种有效的方法(具有正确的索引)使用相关的子查询:

select t.*
from t
where t.time = (select max(t2.time)
                from t t2
                where t2.pin = t.pin
               );

正确的索引位于(pin, time)上。

另一种常用的方法使用窗口函数:

select t.*
from (select t.*,
             row_number() over (partition by pin order by time desc) as seqnum
      from t
     ) t
where seqnum = 1;
相关问题