0

我有一个如下表结构。我需要选择最高的位置User_Id =100和位置。我的查询的输出应导致:User_sub_id = 1time_used = minimum of allTimestamp

US;1365510103204;NY;1365510103;100;1;678;

我的查询看起来像这样。

select * 
from my_table 
where CODE='DE' 
  and User_Id = 100 
  and User_sub_id = 1 
 and time_used = (select min(time_used) 
                  from my_table 
                  where CODE='DE' 
                    and User_Id=100 
                    and User_sub_id= 1);

这将返回所有 4 行。我只需要 1 个,即时间戳最高的那个。非常感谢

CODE:   Timestamp:  Location:   Time_recorded:  User_Id:    User_sub_Id:    time_used
"US;1365510102420;NY;1365510102;100;1;1078;
"US;1365510102719;NY;1365510102;100;1;978;
"US;1365510103204;NY;1365510103;100;1;878;
"US;1365510102232;NY;1365510102;100;1;678;
"US;1365510102420;NY;1365510102;100;1;678;
"US;1365510102719;NY;1365510102;100;1;678;
"US;1365510103204;NY;1365510103;100;1;678;
"US;1365510102420;NY;1365510102;101;1;678;
"US;1365510102719;NY;1365510102;101;1;638;
"US;1365510103204;NY;1365510103;101;1;638;
4

3 回答 3

2

另一个可能更快的解决方案是使用窗口函数:

select * 
from (
  select code,
         timestamp,
         min(time_used) over (partition by user_id, user_sub_id) as min_used,
         row_number() over (partition by user_id, user_sub_id order by timestamp desc) as rn,
         time_used,
         user_id, 
         user_sub_id
  from my_table 
  where CODE='US' 
    and User_Id = 100 
    and User_sub_id = 1 
) t
where time_used = min_used
  and rn = 1;

这只需要扫描表一次,而不是像您使用子选择的解决方案那样扫描两次。

我强烈建议重命名该列timestamp

首先这是一个保留字,不推荐使用它们。

其次,它没有记录任何东西——它本身就是一个可怕的名字。time_used好多了,你应该找到类似的东西timestamp。那是“录制时间”、“到期时间”、“到期时间”还是完全不同的东西?

于 2013-05-03T12:37:33.183 回答
1

然后试试这个:

select *
from my_table
where CODE='DE'
  and User_Id=100
  and User_sub_id=1
  and time_used=(
    select min(time_used)
    from my_table
    where CODE='DE'
    and User_Id=100 and User_sub_id=1
  )
order by "timestamp" desc --   <-- this adds sorting
limit 1; --   <-- this retrieves only one row
于 2013-05-03T12:16:15.140 回答
0

将以下条件添加到您的查询中

ORDER BY Timestamp DESC, LIMIT 1

于 2013-05-03T12:18:23.587 回答