2015-09-04 141 views
3

你好,我有如下表設計由Max日期選擇ACCOUNT_ID

 
ID  account_id  score  date 
------------------------------------------  
1  500    4    x 
2  764    4    x 
3  500    6    x 
4  500    7    x 
5  764    5    x 

我試圖讓所有行與最新的ACCOUNT_ID進入

所以我的代碼應該返回

 
ID  account_id  score  date 
------------------------------------------  
4  500    7    x 
5  764    5    x

我試過下面的代碼,但它似乎返回的第一個條目,但與最新日期

SELECT account_id,score, max(date) from table group by account_id 

回答

0

案例1:如果id是自動增量列或MAX(ID)表示最新行。

select * from 
(select * from table_name 
order by id desc) temp 
group by account_id 

案例2:如果date列決定最新行再由dateorder clausegroup clause更換id

+0

哇,太感謝你了,我決定去與案例1。 – Amanda1990

0

嘗試它 -

SELECT distinct a.id,a.account_id,b.score,b.date 
FROM mytable b 
JOIN 
(
SELECT account_id,MAX(id) AS id 
FROM mytable 
GROUP BY account_id 
) a ON a.account_id=b.account_id 
ORDER BY a.id; 
0
SELECT a.* 
FROM table a 
INNER JOIN (
    SELECT `account_id`,MAX(`date`) AS latest FROM table GROUP BY account_id 
) b 
ON a.`date` = b.`latest` AND a.`account_id` = b.`account_id` 
ORDER BY `date` DESC 

參考:

Using ORDER BY and GROUP BY together

0

嘗試使用此查詢它工作正常

Select a.account_id,a.score,a.date 
from authors as a 
join 
(Select account_id,max(date) as date 
from authors 
group by account_id) as d 
on(d.date=a.date)