Home > Back-end >  Return the corresponding categorical values for min and max functions in group by SQL
Return the corresponding categorical values for min and max functions in group by SQL

Time:02-28

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

CodePudding user response:

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;
  • Related