简体   繁体   English

如何检查上个月的状况

[英]HOW TO CHECK CONDITIONS FOR PREVIOUS MONTH

My table is like我的桌子就像

RUNDATE    TRANSACTION_ID   CUSTOMER_ID   TRANSACTION_TYPE
18/10/2020  2464            4007715       T9

I am trying to get customer_ids where they didn't do any transactions previous month and made transactions with at least 2 transaction_type at this_month.While doing this I am converting rundate to MM-YYYY format.我正在尝试获取上个月没有进行任何交易的 customer_ids,并在 this_month 进行了至少 2 个 transaction_type 的交易。这样做时,我将运行日期转换为 MM-YYYY 格式。 What I've done for getting previous month and this month on MM-YYY format is :我为获得上个月和本月的 MM-YYY 格式所做的工作是:

SELECT EXTRACT( MONTH FROM RUNDATE )|| '-' || EXTRACT(YEAR FROM RUNDATE ) AS MONTH_YEAR,
TRANSACTION_TYPE,
CUSTOMER_ID,
TRANSACTION_ID,
EXTRACT( MONTH FROM PREV_MONTH)|| '-' || EXTRACT(YEAR FROM PREV_MONTH) AS PREV_MONTH_YEAR FROM
(
SELECT TRANSACTION_ID,RUNDATE,CUSTOMER_ID,TRANSACTION_TYPE, ADD_MONTHS(rundate ,-1) as PREV_MONTH
FROM TRANSACTIONS
)

and this is what i got:这就是我得到的:

PREV_MONTH_YEAR MONTH_YEAR  TRANSACTION_TYPE   CUSTOMER_ID
9-2020          10-2020      T9                4007715


But the problem is I couldn't figure how to check my conditions for both PREV_MONT_YEAR AND MONTH_YEAR at the same time但问题是我不知道如何同时检查 PREV_MONT_YEAR 和 MONTH_YEAR 的条件

You can use window functions: You can aggregate by month and use window functions:您可以使用窗口函数:您可以按月聚合并使用窗口函数:

SELECT t.*
FROM (SELECT t.CUSTOMER_ID, TRUNC(RUNDATE, 'MON') as RUN_MONTH,                 
             COUNT(*) as cnt_this_month,
             LAG(TRUNC(RUNDATE, 'MON')) OVER (PARTITION BY CUSTOMER_ID) as PREV_RUNMONTH
       FROM TRANSACTIONS t
       GROUP BY CUSTOMER_ID, TRUNC(RUNDATE, 'MON')
      ) t
WHERE cnt_this_month >= 2 and 
      (prev_runmonth is null or prev_runmonth < run_month - interval '1' month);

Note: This truncates the date to the first day of the month.注意:这会将日期截断为月份的第一天。 I prefer working with dates rather than strings.我更喜欢使用日期而不是字符串。 Of course, you can use to_char(runmonth, 'YYYY-MM') if you prefer strings.当然,如果您更喜欢字符串,可以使用to_char(runmonth, 'YYYY-MM')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM