简体   繁体   中英

Get the records from previous year from same account ids present at both time periods

I am trying to get count of transactions for years 2019 and 2021 and compare them with corresponding months for the same customers who have been in 2019 and 2021.example - compare users from 2019 jan who are also there in 2021 Jan and count their transactions and then compare them. I have tried to do a self join but I am getting same number of transactions for both the transactions, any help on tweaking or telling where I have written the query wrongly will help me a lot.

Select datepart(r2021.transdate, year), datepart(r2021transdate,month)
,Count (r2021.transaction_id)  as transidcount2021
Count (r2019.transaction_id) as transidcount2019

From rewards r2021
Join rewards r2019
On datepart(r2021.transdate, year)=datepart(r2019.transdate, year)+2
And 
datepart(r2021transdate,month) =datepart(r2019transdate,month)
And
R2021.accountid = r2019.accountid
Where 
datepart(r2021.transdate, year) =2021
Group by 1,2

Now if I run this I get same values for transcount2019 and transcount2021 for all months in 2021.

compare users from 2019 jan who are also there in 2021 Jan and count their transactions and then compare them

This suggests that you want a table with columns such as:

  • month of the year
  • users in 2019
  • transactions in 2019
  • users in 2021
  • transactions in 2021
  • users in both years
  • transactions in both years

That suggests two levels of aggregation:

select month,
       count(*) filter (where cnt_2019 > 0) as customers_2019,
       sum(cnt_2019) as transactions_2019,
       count(*) filter (where cnt_2021 > 0) as customers_2021,
       sum(cnt_2021) as transactions_2021,
       count(*) filter (where cnt_2019 > 0 and cnt_2021 > 0) as customers_both,
       sum(cnt_2019 + cnt_2021) filter (where cnt_2019 > 0 and cnt_2021 > 0) as transactions_both
from (select accountid, extract(month from trandate) as month,
             count(*) filter (where extract(year from trandate) = 2019) as cnt_2019,
             count(*) filter (where extract(year from trandate) = 2021) as cnt_2021
      from rewards r
      group by accountid, month
     ) am
group by month;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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