2014-04-03 97 views
0

假設我有這樣一個表:SQL,難取數據查詢

+-----+---------+-------+ 
| ID | TIME | DAY | 
+-----+---------+-------+ 
| 1 | 1 | 1 | 
| 2 | 2 | 1 | 
| 3 | 3 | 1 | 
| 1 | 1 | 2 | 
| 2 | 2 | 2 | 
| 3 | 3 | 2 | 
| 1 | 1 | 3 | 
| 2 | 2 | 3 | 
| 3 | 3 | 3 | 
| 1 | 1 | 4 | 
| 2 | 2 | 4 | 
| 3 | 3 | 4 | 
| 1 | 1 | 5 | 
| 2 | 2 | 5 | 
| 3 | 3 | 5 | 
+-----+---------+-------+ 

我要取的代表2點的ID其拿到在過去3天的時間之和最大的一個表(指3〜在5天列)

所以正確的結果將是:

+-----+---------+ 
| ID | SUM  | 
+-----+---------+ 
| 3 | 9 | 
| 2 | 6 | 
+-----+---------+ 

原始表是更大,更復雜。所以我需要一個通用的方法。

在此先感謝。

+1

你嘗試過什麼?你可以用你試過的代碼編輯你的文章嗎? – bobkingof12vs

+0

你的PK是在所有列上形成的? – Strawberry

回答

1

所以我剛剛得知,MySQL的使用LIMIT代替TOP ...

fiddle

CREATE TABLE tbl (ID INT,tm INT,dy INT); 

INSERT INTO tbl (id, tm, dy) VALUES 
(1,1,1) 
,(2,2,1) 
,(3,3,1) 
,(1,1,2) 
,(1,1,1) 


SELECT ID 
     ,SUM(SumTimeForDay) SumTimeFromLastThreeDays 
    FROM (SELECT ID 
       ,SUM(tm) SumTimeForDay 
      FROM tbl 
     GROUP BY ID, dy 
     HAVING dy > MAX(dy) -3) a 
GROUP BY id 
ORDER BY SUM(SumTimeForDay) DESC 
LIMIT 2 
0
select t1.`id`, sum(t1.`time`) as `sum` 
from `table` t1 
inner join (select distinct `day` from `table` order by `day` desc limit 3) t2 
     on t2.`da`y = t1.`day` 
group by t1.`id` 
order by sum(t1.`time`) desc 
limit 2