如何获得 SQL 中所有月份的交易金额 > 1000

How do I get transactions amount > 1000 of all months in SQL

我一直在尝试拉所有月份交易额大于1000的客户。到目前为止,这是我尝试过的。但是我做个人客户测试的时候好像没用。

Select customer 
,extract(month from trans_date) as mth
,extract(year from trans_date) as yr
,sum(trans_amount) as amt
, case when mth in (8) and amt > 1000 then 1 else 0 end as aug
, case when mth in (9) and amt > 1000 then 1 else 0 end as sep
, case when mth in (10) and amt > 1000 then 1 else 0 end as oct
, case when mth in (11) and amt > 1000 then 1 else 0 end as nov
, case when mth in (12) and amt > 1000 then 1 else 0 end as de_c

from transaction 
group by 1,2,3
having (aug = 1 and sep = 1 and oct=1 and nov=1 and de_c = 1) 

您可能想尝试像这样使用 Over(分区依据)。

Select customer 
,extract(month from trans_date) as mth
,extract(year from trans_date) as yr
,sum(trans_amount) over (partition by customer , extract(month from trans_date)) as 
total
From transaction 
Order by total desc
Select customer 
  ,extract(month from trans_date) as mth
  ,extract(year from trans_date) as yr
  ,sum(trans_amount) as amt
from transaction
-- filter only those months you want to check, e.g.
where trans_date between date '2021-08-01' and date '2021-12-31' 
group by 1,2,3
-- check that every month there was an individual transaction over 1000
qualify 
   min(max(trans_amount))
   over (partition by customer) > 1000

编辑:

只获取没有详细信息行的客户的相同逻辑:

select customer
from 
 (
    Select customer, max(trans_amount) as maxamt
    from transaction
    -- filter only those months you want to check, e.g.
    where trans_date between date '2021-08-01' and date '2021-12-31' 
    group by 
       customer
      ,trunc(trans_date, 'mon') -- for every month
 ) as dt
group by customer
-- check that every month there was an individual transaction over 1000
having min(maxamt) > 1000

假设您的数据是每个客户每月一条记录。

每个月 trans_amt > 1000 的唯一身份客户:

select customer
from transaction
group by customer
having count(1) = count(case when trans_amt > 1000 then 1 else 0 end)

仅获取每个月 trans_amt > 1000 的客户的所有记录:

select customer, trans_date, trans_amt
from transaction
qualify count(1) over (partition by customer) = count(case when trans_amt > 1000 then 1 else 0 end) over (partition by customer)