简体   繁体   中英

Return the corresponding categorical values for min and max functions in group by SQL

I have a transaction table with the following columns: TRANSACTION_ID,USER_ID,MERCHANT_NAME,TRANSACTION_DATE,AMOUNT

-1) query to find the first merchant a user transacts on

-2) query to find the last merchant a user transacts on

I tried the following

This query should work as group by picks up categorical value from the 1st entry

-)select USER_ID, Min(TRANSACTION_DATE),MERCHANT_NAME from transactions
Group by USER_ID

Using ROW_NUMBER we can try:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY USER_ID ORDER BY TRANSACTION_DATE) rn1,
              ROW_NUMBER() OVER (PARTITION BY USER_ID ORDER BY TRANSACTION_DATE DESC) rn2
    FROM transactions
)

SELECT USER_ID,
       MAX(CASE WHEN rn1 = 1 THEN MERCHANT_NAME END) AS FIRST_MERCHANT_NAME,
       MAX(CASE WHEN rn2 = 1 THEN MERCHANT_NAME END) AS LAST_MERCHANT_NAME
FROM cte
GROUP BY USER_ID;

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