Redshift

到該月從某個月組計算 12 個月前的訂單

  • April 22, 2019

我想創建一個表,其中包含從目前月份到 12 個月前的月份計數訂單。我有帶有 create_date 和 order_id 的數據。因此,我需要將日期轉換為 yyyymm 的格式,併計算所選月份的所有訂單,並總結 12 個月前的所有訂單。

結果應如下所示:

在此處輸入圖像描述

我從這個查詢開始,但它只計算所選月份的訂單,不包括前幾個月的訂單。

SELECT TO_CHAR(create_date,'yyyymm') AS yyyymm,
      COUNT(order_id ) AS Number_of_orders_12_month_period
FROM Orders 
WHERE TO_CHAR(create_date,'yyyymm') BETWEEN DATEADD(month,-12,create_date) AND TO_CHAR(create_date,'yyyymm')  
group by 1

所以我設法用這個查詢來修復它

SELECT TO_CHAR(create__date,'yyyymm') as month_id
 , LAG(count(order_id), 0) OVER (ORDER BY create__date) +
   LAG(count(order_id), 1) OVER (ORDER BY create__date) +
   LAG(count(order_id), 2) OVER (ORDER BY create__date) +
   LAG(count(order_id), 3) OVER (ORDER BY create__date) +
   LAG(count(order_id), 4) OVER (ORDER BY create__date) +
   LAG(count(order_id), 5) OVER (ORDER BY create__date) +
   LAG(count(order_id), 6) OVER (ORDER BY create__date) +
   LAG(count(order_id), 7) OVER (ORDER BY create__date) +
   LAG(count(order_id), 8) OVER (ORDER BY create__date) +
   LAG(count(order_id), 9) OVER (ORDER BY create__date) +
   LAG(count(order_id), 10) OVER (ORDER BY create__date) +
   LAG(count(order_id), 11) OVER (ORDER BY last_day_create__date)  as Number_of_orders_12_month_period 
FROM orders GROUP BY create__date;

它看起來很奇怪,但它給出了正確的答案並且相對快速

我沒有使用 Redshift 的經驗,但是

WHERE TO_CHAR(create_date,'yyyymm') BETWEEN DATEADD(month,-12,create__date) AND TO_CHAR(create_date,'yyyymm')  

在我看來不對。您不想create_date與自身比較,您想將其與 比較current_date,並且您想在每個日期轉換為一個月後進行比較。例如:

WHERE TO_CHAR(create_date,'yyyymm') BETWEEN TO_CHAR(DATEADD(MONTH,-12,current_date),'yyyymm') AND TO_CHAR(current_date,'yyyymm')

引用自:https://dba.stackexchange.com/questions/235287