简体   繁体   中英

How can I find attribute of oldest entry per user in 1:n relationship between user and entries?

In PostgreSQL , I have 2 tables:

  • Users ( UserID (PK int), UserName (character varying))
  • Visits ( VisitID (PK int), UserID (FK Users, int), VisitDate (date), VisitReason (int), Greeting (character varying) )

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.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM