2017-03-17 43 views
2

哇這個問題真的很難簡明扼要地制定。所以,這裏的數據:查找具有相關最大日期行列匹配值的表的行嗎?

Person: 
+----+---------+ 
| ID | Name | 
+----+---------+ 
| 1 | Bob  | 
| 2 | Alice | 
| 3 | Greg | 
| 4 | Lisa | 
+----+---------+ 

Activity: 
+----+----------+------------+----------+ 
| ID | PersonID | Date  | Activity | 
+----+----------+------------+----------+ 
| 1 | 1  | 2017-03-01 | foo  | 
| 2 | 1  | 2017-03-02 | bar  | 
| 3 | 2  | 2016-12-01 | foo  | 
| 4 | 3  | 2017-01-15 | foo  | 
+----+----------+------------+----------+ 

我想回到所有Person行,其最近期的Activityfoo

Return: 
+----+---------+ 
| ID | Name | 
+----+---------+ 
| 2 | Alice | 
| 3 | Greg | 
+----+---------+ 

謝謝!

+0

你嘗試過什麼?你使用哪個dbms? – jarlh

+0

我正在使用SQLite,但如果絕對必要,可以使用MySQL。我實際上是通過flask-sqlalchemy來做這件事的,我當然可以用代碼來過濾它,但是我覺得SQL會更快。 – Rick

+0

我試着修改這個答案,但無法讓它工作得很正確:http://stackoverflow.com/questions/7745609/sql-select-only-rows-with-max-value-on-a-column – Rick

回答

3

MySQL的

select P3.* 
from 
(
select PersonID, max(Date) as mDate 
from Activity 
group by PersonID 
) a1 
inner join Activity A2 
    on A2.PersonID = A1.PersonID 
    and A2.Date = A1.mDate 
inner join Person P3 
    on P3.ID = A2.PersonID 
where A2.Activity = 'Foo' 
and not exists (select 1 -- This is for those who did both on one day 
       from Activity A4 
       where A4.Activity = 'Bar' 
       and A4.PersonID = A1.PersonID 
       and A4.Date = A1.mDate) 

和SQL服務器/甲骨文(樂趣)

with CTE as 
(
select A1.*, row_number() over(partition by PersonID order by Date desc) as r_ord 
from Activity A1 
) 
select P2.* 
from Person P2 
inner join CTE 
    on CTE.PersonID = P2.ID 
where CTE.r_ord = 1 
and CTE.Activity = 'Foo' 
+0

這似乎工作得很好,除了兩個活動日期相同的情況。 (未說明的)意圖是找到「欺騙」但不「禁止」的人。我的數據有點骯髒,我可能只是把它清理乾淨。 – Rick

+1

@Rick查看編輯 – JohnHC

1
select * from Person where ID in 
(select PersonID from (select Top 1 * from Activity where PersonID = Person.ID order by Activity.Date desc) Tmp where Tmp.Activity <> 'bar') 
相關問題