2013-05-03 114 views
0

我有一個像下面這樣的表結構。我需要選擇User_Id =100User_sub_id = 1time_used = minimum of all以及其中Timestamp最高的那一行。我的查詢輸出結果如下:調試SQL查詢

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; 
+0

您正在使用哪些DBMS? Postgres的?甲骨文? – 2013-05-03 12:21:09

+0

@a_horse_with_no_name。 Postgres – 2013-05-03 12:24:07

回答

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 
+0

使用聚合函數時,您不一定需要使用group。 – 2013-05-03 12:19:50

+0

@a_horse_with_no_name:感謝您的信息,我認爲這是必需的。 – 2013-05-03 12:23:55

+0

@MatteoTassinari:thánks..it作品:) – 2013-05-03 12:27:59

0

添加到您的查詢下列條件

ORDER BY時間戳DESC,LIMIT 1

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。那是「錄音時間」,「到期時間」,「到期時間」還是完全不同的東西?

+0

感謝您的回答,正如您所指出的那樣,該列實際上未被命名爲'timestamp',因爲它太長而被稱爲'calculation_begin_timestamp',所以我只使用'timestamp'。 – 2013-05-06 10:45:14