簡體   English   中英

SQL 查詢獲得在兩個不同季度購買過相同產品的客戶 - 日期范圍

[英]SQL query to get customers who have purchased same product in two different quarters - Date Ranges

我有一個包含以下列的表Customer_Order_Data

  1. 客戶ID
  2. order_id
  3. product_id
  4. 數量
  5. 訂購日期

我想找到在兩個不同季度(2020 年第一季度(1 月至 3 月)和第二季度(4 月至 6 月))購買相同產品 ( product_id ) 的客戶。 對於這兩個季度,購買數量應大於 5。我還有一個額外要求,即顯示所選行的最頻繁購買數量和最近購買數量。

假設我有以下數據 -

訂單編號 客戶ID product_id 數量 訂購日期
00001 A B C D B019 7 2020-01-01
00002 A B C D B019 6 2020-05-23
00003 EFGH B018 8 2020-01-12
00004 A B C D B019 7 2020-02-14
00005 EFGH B018 6 2020-04-18
00006 A B C D B019 7 2020-04-19
00007 EFGH B018 8 2020-03-12

我想過濾掉在 Q1 和 Q2 購買相同產品且quantity > 5的客戶。 我想根據 customer_id 對行進行分組。

預期結果 -

客戶ID product_id 最常購買 最近購買的
A B C D B019 7 6
EFGH B018 8 6

我試過的查詢 -

select t.*
from mytable t
where (
    select count(*) 
    from mytable t1 
    where 
        t1.customer_id = t.customer_id 
        and t1.product_id = t.product_id 
        and t1.quantity > 5
        and t1.order_date BETWEEN '2020-01-01 00:00:00' AND '2020-03-31 23:59:59'
) > 1
and t.order_date BETWEEN '2020-04-01 00:00:00' AND '2020-06-30 23:59:59'
and t.quantity > 5;

此查詢未正確過濾掉在兩個季度都購買了相同產品的客戶。 另外,我不明白如何為產品添加最常購買數量和最近購買數量的虛擬列

如果我理解正確:這些是相當復雜的約束。 但它似乎很適合 window 函數和聚合:

select customer_id, product_id,
       max(case when seqnum = 1 then quantity end) as most_recent_quantity,
       max(case when cpq_cnt = max_cpq_cnt then quantity end) as most_common_quantity
from (select t.*,
             max(cpq_cnt) over (partition by customer_id, product_id) as max_cpq_cnt
      from (select t.*,
                   row_number() over (partition by customer_id, product_id order by order_date desc) as seqnum,
                   count(*) over (partition by customer_id, product_id, quantity) as cpq_cnt
            from mytable t
            where t.order_date >= '2020-01-01' and
                  t.order_date < '2020-07-01' and
                  t.quantity > 5
           ) t
     ) t
group by customer_id, product_id
having min(order_date) < '2020-04-01' and
       max(order_date) >= '2020-04-01';

最里面的子查詢執行以下操作:

  • 它將行過濾到您關心的時間范圍。
  • 它按order_date枚舉每個客戶/產品的行,以便您確定最近的數量。
  • 它計算每個數量出現的次數。

然后中間子查詢計算數量的最大值。

最后,外部子查詢執行以下操作:

  • 它使用條件聚合來獲取最新的數量。
  • 它使用條件聚合來獲取最頻繁的數量。
  • 它過濾結果以確保每個季度最多有一個訂單。

暫無
暫無

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

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