Reputation: 690
I checked the following questions:
Fetch the row which has the Max value for a column
Columns : account_number, app_guid, time_event_published(epoch time).
I want the latest row of each app_guid
for a given account_number
PLUS oldest time_event_published
of the same account_number
for each app_guid
in another column of the latest row.
SELECT id, account_number, app_guid, time_event_published , <oldest_time_event_published_for_2152331553409959696> FROM (
SELECT id, account_number, app_guid, time_event_published,
RANK() OVER (PARTITION BY app_guid ORDER BY time_event_published DESC) dest_rank
FROM event where account_number=2152331553409959696
) where dest_rank = 1;
I am only able to think of another DB hit with same query with ASC
. Is there any other way and how to approach this requirement?
DB Entries:
2152331553409959696, TEST-ONE-APP_GUID, 25-JAN
2152331553409959696, TEST-ONE-APP_GUID, 1-JAN
2152331553409959696, TEST-TWO-APP_GUID, 25-FEB
2152331553409959696, TEST-TWO-APP_GUID, 1-FEB
Required Result:
2152331553409959696, TEST-ONE-APP_GUID, 25-JAN, 1-JAN
2152331553409959696, TEST-TWO-APP_GUID, 25-FEB, 1-FEB
Upvotes: 0
Views: 426
Reputation: 1612
If I understood your question correctly then I think the below SQL will do what you require:
SELECT id, account_number, app_guid, time_event_published , oldest_time_event_published
FROM (
SELECT id, account_number, app_guid, time_event_published,
RANK() OVER (PARTITION BY app_guid ORDER BY time_event_published DESC) dest_rank,
MIN (time_event_published) OVER (PARTITION BY app_guid) oldest_time_event_published
FROM event where account_number=2152331553409959696
) where dest_rank = 1;
Let me know how it works with your data and let us know.
I haven't tested with sample data but I am pretty confident it will work for you!
Ted.
Upvotes: 1
Reputation: 3781
This should work, it's not very attractive though, whether it's better than hitting the table twice depends on performance and readability.
SELECT MAX(CASE WHEN dest_rank = 1 THEN id
ELSE NULL
END
) AS id,
MAX(CASE WHEN dest_rank = 1 THEN account_number
ELSE NULL
END
) AS account_number,
app_guid,
MAX(CASE WHEN dest_rank = 1 THEN time_event_published
ELSE NULL
END
) AS time_event_published,
MAX(CASE WHEN dest_rank_asc = 1 THEN time_event_published
ELSE NULL
END
) AS earliest_time_event_published
FROM (SELECT id,
account_number,
app_guid,
time_event_published,
RANK() OVER
( PARTITION BY app_guid
ORDER BY time_event_published DESC
) dest_rank,
RANK() OVER
( PARTITION BY app_guid
ORDER BY time_event_published ASC
) dest_rank_asc,
FROM event
WHERE account_number=2152331553409959696
)
GROUP
BY app_guid;
Upvotes: 0