溫馨提示×

如何在casewhen中嵌套使用其他SQL函數(shù)

小樊
84
2024-09-07 04:46:24
欄目: 云計(jì)算

在 SQL 中,可以在 CASE WHEN 語句中嵌套使用其他 SQL 函數(shù)

SELECT customer_id,
       first_name,
       last_name,
       CASE
           WHEN total_orders >= 10 THEN 'Frequent Customer'
           WHEN total_orders < 10 AND total_orders > 0 THEN 'Occasional Customer'
           ELSE 'New Customer'
       END AS customer_type,
       CASE
           WHEN DATEDIFF(CURRENT_DATE, last_order_date) <= 30 THEN 'Active'
           WHEN DATEDIFF(CURRENT_DATE, last_order_date) > 30 AND DATEDIFF(CURRENT_DATE, last_order_date) <= 60 THEN 'Inactive'
           ELSE 'Dormant'
       END AS customer_activity
FROM (
    SELECT customer_id,
           first_name,
           last_name,
           COUNT(*) AS total_orders,
           MAX(order_date) AS last_order_date
    FROM customers
    LEFT JOIN orders ON customers.customer_id = orders.customer_id
    GROUP BY customers.customer_id
) AS subquery;

在這個(gè)示例中,我們首先創(chuàng)建了一個(gè)子查詢(subquery),該子查詢計(jì)算每個(gè)客戶的訂單總數(shù)和最后一次下單日期。然后,在主查詢中,我們使用 CASE WHEN 語句為客戶分配類型(如“頻繁客戶”,“偶爾客戶”和“新客戶”),并根據(jù)他們的活動(dòng)狀態(tài)(如“活躍”,“不活躍”和“休眠”)進(jìn)行分類。

在這個(gè)例子中,我們使用了 COUNT(*)MAX(order_date) 函數(shù)來計(jì)算每個(gè)客戶的訂單總數(shù)和最后一次下單日期,然后在主查詢中使用 CASE WHEN 語句對(duì)這些值進(jìn)行條件判斷。同樣地,你可以在 CASE WHEN 語句中使用其他 SQL 函數(shù)來滿足你的需求。

0