简体   繁体   中英

Pull a Row Value associated with the Max Value of a Column

We have two tables that we'd like to join, one is a Users table and the other is a Subscriptions Table.

Users table stores columns like • User ID • Name • Email • Account Create Date

Every time a new user joins, a new row is added to this table.

Subscription table stories columns like • Subscription ID • User ID • Subscription Created At • Subscription Ended At • Subscription Status

Every time a user RESUBSCRIBES a new row is added. Continuing on their existing subscription does not create a new row.

Our goal is create a query that returns the following columns • User ID • Email • Account Create Date • Subscription Status (Active/Canceled/NULL)

However, when we attempt to do the query below it returns multiple rows for creators that have multiple subscriptions.

 SELECT
       u.user_id,
       u.email,
       u.account_create_date
       s.subscription_status
    FROM
       users as u
    INNER JOIN
       subscriptions as s
       on s.user_id = u.user_id

How can we write a query where it pulls the Subscription Status for the Subscription with the Max Subscription Created At date?

This is how I would do it. Not sure if it is the best way. ;)

Join a subquery of the User ID and max Max Subscription Created At date and use that to filter only those results.

SELECT
   u.user_id,
   u.email,
   u.account_create_date
   s.subscription_status
FROM
   users as u
INNER JOIN
   subscriptions as s
   on s.user_id = u.user_id
INNER JOIN 
   (SELECT s.user_id, 
   MAX(s.subscription_created_at) AS subscription_created_at
   FROM subscriptions 
   GROUP BY s.user_id) max_s
   ON max_s.user_id = s.user_id

WHERE s.subscription_created_at = max_s.subscription_created_at

A common way uses window functions:

SELECT u.user_id, u.email, u.account_create_date
       s.subscription_status
FROM users u JOIN
     (SELECT s.*,
             ROW_NUMBER() OVER (PARTITION BY s.user_id ORDER BY s.created_at DESC) as seqnum
      FROM subscriptions s
     ) s
     ON s.user_id = u.user_id AND s.seqnum = 1;

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-2024 STACKOOM.COM