Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

sql - Selecting all corresponding fields using MAX and GROUP BY

I have this table :

alt text

And I would like to make a request that would return for each deal_id the row with the highest timestamp, and the corresponding status_id.

So for this example, I would have returned 2 rows :

1226, 3, 2009-08-18 12:10:25
1227, 2, 2009-08-17 14:31:25

I tried to do it with this query

SELECT deal_id, status_id, max(timestamp) FROM deal_status GROUP BY deal_id

but it would return the wrong status_id :

1226, 1, 2009-08-18 12:10:25
1227, 1, 2009-08-17 14:31:25
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

without a single primary key field, I think your best bet is:

select * from deal_status
inner join
  (select deal_id as did, max(timestamp) as ts
  from deal_status group by deal_id) as ds
  on deal_status.deal_id = ds.did and deal_status.timestamp = ds.ts

this still won't work if you allow having two different statuses for the same product at the same time


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...