簡體   English   中英

添加新的查找列 - 客戶在 30 天內退貨

[英]Add new lookup column - customer return within 30 days

問題的背景:當客戶在給定日期在雜貨店購買商品時,它被記錄為交易表中的一行,我想在 select 語句中添加一個“查找”列以檢查同一客戶是否有另一個30天內交易。 “30 天”是當前交易日期 + 30,新的查找列將添加到 select * 的末尾。

db.transaction : Customer_ID, Transaction_ID, Transaction Date

查詢退貨Customer_ID, Transaction_ID, Transaction Date, **Return within 30 days (Yes/No)**

我認為新的查找列可能是一個案例表達式,但我不知道如何獲取同一客戶的下一個可用交易日期並與當前行中的交易日期進行比較。

case 
   when datediff(day, transaction_date,  "next available date")<=30 then 'Yes
   else 'No'
end as 'return_within_30_days'

謝謝你的幫助! (我正在使用 SQL 服務器)

使用LEAD到客戶的下一筆交易。 您的“下一個可用日期”轉換為

LEAD (transaction_date)
  OVER (PARTITION BY customer_id ORDER BY transaction_date)

完整的查詢:

select
  customer_id,
  transaction_id,
  transaction_date,
  case 
   when datediff(day, 
                 transaction_date,
                 lead (transaction_date)
                   over (partition by customer_id order by transaction_date)
                ) <= 30
   then 'YES'
   else 'NO'
  end as return_within_30_days
from mytable
order by customer_id, transaction_date;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM