Return group by SQL 中最小和最大函数的相应分类值
Return the corresponding categorical values for min and max functions in group by SQL
我有一笔交易 table 包含以下列:
TRANSACTION_ID,USER_ID,MERCHANT_NAME,TRANSACTION_DATE,金额
-1) query to find the first merchant a user transacts on
-2) query to find the last merchant a user transacts on
我尝试了以下方法
此查询应按照从第一个条目中选取分类值的方式进行分组
-)select USER_ID, Min(TRANSACTION_DATE),MERCHANT_NAME from transactions
Group by USER_ID
使用ROW_NUMBER
我们可以尝试:
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;
我有一笔交易 table 包含以下列: TRANSACTION_ID,USER_ID,MERCHANT_NAME,TRANSACTION_DATE,金额
-1) query to find the first merchant a user transacts on
-2) query to find the last merchant a user transacts on
我尝试了以下方法
此查询应按照从第一个条目中选取分类值的方式进行分组
-)select USER_ID, Min(TRANSACTION_DATE),MERCHANT_NAME from transactions
Group by USER_ID
使用ROW_NUMBER
我们可以尝试:
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;