【问题标题】:How do I get transactions amount > 1000 of all months in SQL如何在 SQL 中获取所有月份的交易金额 > 1000
【发布时间】:2022-01-19 17:52:19
【问题描述】:

我一直在尝试拉动所有月份交易金额大于 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) 

【问题讨论】:

  • 任何给定的行都只有一个第 m 个值,因此您的 HAVING 条件永远不会为真。
  • 您的预期结果集到底是什么?

标签: sql teradata


【解决方案1】:
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

【讨论】:

  • 谢谢,这可能有效。但是每个客户都有多行(aug、sep、oct 等的总和)。我想要单行来确定该客户是否符合该规则(每月单独交易超过 1000 笔)。请问我该如何改进呢?
  • @Ben - 如果至少一个月没有交易 > 1000,您是否要排除客户的所有行,或者仅排除该月?这就是为什么上面要求您提供样本数据和所需结果的原因。
  • 您可能想在分区子句中添加yrmth
【解决方案2】:

您可能想尝试使用 Over (partition by) 这样的东西。

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

【讨论】:

    【解决方案3】:

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

    每月获得 trans_amt > 1000 的唯一客户:

    选择客户 从交易 按客户分组 有 count(1) = count(trans_amt > 1000 然后 1 else 0 end 的情况)

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

    选择客户、trans_date、trans_amt 从交易 限定 count(1) over (partition by customer) = count(case when trans_amt > 1000 then 1 else 0 end) over (partition by customer)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-20
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      相关资源
      最近更新 更多