2017-01-01 57 views
0

數據庫中,我有幾百萬結構行的表如下:將多行數以百萬計

UserID | Date  | Points 
1  | 2016-05-01 | 240 
1  | 2016-05-02 | 500 
1  | 2016-05-03 | 650 
2  | 2016-05-01 | 122 
2  | 2016-05-02 | 159 
2  | 2016-05-03 | 290 

等等等等。

我需要找到Points之間的差異2016-05-032016-05-01之間的每個ID,按差異排序Points,並返回頂部~100。我的數據庫包含數億行,因此它需要快速操作。

我從哪裏開始?我正在尋找group_concat,但我不確定這是否是這個用例的正確功能。

+0

是這些日期'2016年5月3日和2016-05-01'靜態所有用戶ID? – bhantol

+0

@bhantol他們,是的。每個用戶將有一個日期的條目。 – DannyF247

+0

表有主鍵列嗎? –

回答

0

此查詢正在工作,它不是非常快速,但可以作出。

select tbl.id as UserId, ((select t.points from tbl t where date = '2016-05-03' and t.id=tbl.id)-(select t.points from tbl t where date = '2016-05-01' and t.id=tbl.id)) as diff from tbl group by id order by diff limit 100; 

運行這一點,讓我知道,如果這是需要很長時間。

0

你應該有子查詢像下面

SELECT 
    user_id, 
    (select points from tbl_test where tbl_test.date_of='2016-05-03' and user_id=t1.user_id)-t1.points as difference_in_points 
FROM `tbl_test` as t1 
WHERE date_of='2016-05-01' order by difference_in_points desc 
limit 100 
+0

這對你有幫助 –

0

加入表本身。

SELECT t1.user_id, t1.points - t2.points as diff 
FROM yourTable AS t1 
JOIN yourTable AS t2 ON t1.user_id = t2.user_id 
WHERE t1.date = '2016-05-03' 
AND t2.date = '2016-05-01' 
ORDER BY diff DESC 
LIMIT 100