The conditions are:
1) We have a table with 'email' text field, 'timestamp' field and many other columns.2) There can be many equal emails and timestamps.
3) We need to query all table columns for all the (most recent) (distinct) emails. In other words for each unique email select max timestamp and all other correspondent columns.
4) Main difficulty is if we have equal emails and time stamps we will have more than 1 returned record per email, which is wrong.
The salvation solution is:
SELECT *
FROM (SELECT *,
RANK() OVER (PARTITION BY email ORDER BY time_stamp DESC) number
FROM My_Table
)sorted_table WHERE number = 1
The Explanations are:
1) The subquery groups the table by email and then orders by the timestamp2) An extra column 'number' is added to number the grouped emails, 1 is for the most recent one(MAX DATE). It is done using RANK() OVER.
3) The outer main query just selects everything with number 1 (most recent).
??????????
4) PROFIT
No comments:
Post a Comment