In PostgreSQL , I have 2 tables:
1 user can visit me n times. Each visit entry has a date.
Now I want to query a list of the users with the Greeting
of their oldest ( VisitDate
) visit with VisitReason=123
. (1 row per user.) (I'm not interested in users without a relevant visit.)
What's the easiest way to do this in PostgreSQL?
Performance is not important. It's for a one-time task.
The cleanest way I can think of, is using FETCH FIRST ROWS WITH TIES
clause, with respect to ROW_NUMBER
that ranks 1 each UserID's first date.
SELECT UserID, Greeting
FROM visits
WHERE VisitReason = 123
ORDER BY ROW_NUMBER() OVER(PARTITION BY UserID ORDER BY VisitDate)
FETCH FIRST 1 ROWS WITH TIES
If you need to catch users names too, it requires an additional join (left with respect to users table) operation:
SELECT u.UserName, v.Greeting
FROM users u
LEFT JOIN visits v ON u.UserID = v.UserID
WHERE v.VisitReason = 123
ORDER BY ROW_NUMBER() OVER(PARTITION BY u.UserID ORDER BY v.VisitDate)
FETCH FIRST 1 ROWS WITH TIES
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.