2010-04-12 85 views
1

我有一張表記錄給定服務在給定日期傳輸的數據量。每天爲特定服務輸入一條記錄。SELECT set of most recent id,amount FROM table,where id occurrence many times

我希望能夠檢索一組服務的最新amount

實施例的數據集:

serviceId | amount | date 
------------------------------- 
1   | 8  | 2010-04-12 
2   | 11  | 2010-04-12 
2   | 14  | 2010-04-11 
3   | 9  | 2010-04-11 
1   | 6  | 2010-04-10 
2   | 5  | 2010-04-10 
3   | 22  | 2010-04-10 
4   | 17  | 2010-04-19 

所需應答(服務ID 1,2,3):

serviceId | amount | date 
------------------------------- 
1   | 8  | 2010-04-12 
2   | 11  | 2010-04-12 
3   | 9  | 2010-04-11 

所需應答(服務ID 2,4):

serviceId | amount | date 
------------------------------- 
2   | 11  | 2010-04-12 
4   | 17  | 2010-04-19 

這會檢索相當於每個serviceId運行以下內容的一次:

SELECT serviceId, amount, date 
FROM table 
WHERE serviceId = <given serviceId> 
ORDER BY date DESC 
LIMIT 0,1 

我瞭解如何在X查詢中檢索我想要的數據。我有興趣瞭解如何使用單個查詢或至少少於X個查詢檢索相同的數據。

我很感興趣,看看什麼可能是最有效的方法。該表目前包含28809條記錄。

我明白,還有其他問題,包括選擇最新的一組記錄。我已經審查了三個這樣的問題,但一直無法將解決方案應用於我的問題。

回答

3
select m.* 
from (
    select serviceId, max(date) as MaxDate 
    from MyTable 
    group by serviceId 
) mm 
inner join MyTable m on mm.serviceId = m.serviceId and mm.MaxDate = m.date 

如果您希望通過服務Id篩選,你可以這樣做:

select m.* 
from (
    select serviceId, max(date) as MaxDate 
    from MyTable 
    where serviceId in (1, 2, 3) 
    group by serviceId 
) mm 
inner join MyTable m on mm.serviceId = m.serviceId and mm.MaxDate = m.date 
+0

由於過濾掉一些serviceIds,完美的作品。 – 2010-04-12 21:48:04

0
SELECT serviceId, amount, date 
    FROM table as t 
    WHERE NOT EXIST (
    SELECT * FROM table as x 
     WHERE t.serviceId = x.serviceID AND t.date < x.date 
) 

如果你想比

SELECT serviceId, amount, date 
    FROM table as t 
    WHERE NOT EXIST (
    SELECT * FROM table as x 
     WHERE t.serviceId = x.serviceID AND t.date < x.date 
) 
    AND serviceId in (2, 4) 
相關問題