我想通过比较postgresql中的两列来得到一个具体的答案



我有一个这样的查询:

with base_data as 
( Select
receipt_date,
receipt_value,
receipt_customer_id
From table1 )
Select
count(distinct (receipt_customer_id) , sum(receipt_value)
From
base_data
where
(receipt_date:timestamp <= current_date - interval '1 month' and 
receipt_date: timestamp >= current_date - interval '2 month)

这基本上为我提供了7月和8月的不同客户数量及其收据价值总和,考虑到当前月份为9月我想进一步减少这种情况,只需要不同客户及其收据价值之和对于他们来说,7月份没有收据,即他们在7月份从未与我们交易,但在8月份回来,基本上他们跳过了一个月,然后再次交易。我无法将此条款用英语写在下面,作为问题陈述:请给我8月份与我们交易但7月份没有收据价值的客户的不同数量及其收据总额的数据我希望我能解释一下。我已经为此绞尽脑汁了一段时间,但无法找到解决方案。请帮忙。

当前结果如下计数:120总计:207689我想把它简化为(假设(计数:12总计:7000

我能看到的第一个问题是"7月和8月的接收值之和";;当前查询的返回将取决于它的运行时间(而不是日历月(。让我们把它放在一边,简化/修复(如上所述的查询没有运行(您的查询,使其能够列出8月份的所有交易(我认为现在使用硬编码日期更容易理解(:

Select
receipt_customer_id, sum(receipt_value)
From
table1
where
-- Transacted in August
receipt_date >= '2020-08-01'::timestamp and
receipt_date < '2020-09-01'::timestamp 
group by receipt_customer_id;

我们现在可以在where中添加另一个子句,以筛选出7月份交易总额为$0/NULL(因此交易总额为0美元或根本没有交易(的客户:

Select
receipt_customer_id, sum(receipt_value)
From
table1 t
where
-- Transacted in August
t.receipt_date >= '2020-08-01'::timestamp and 
t.receipt_date < '2020-09-01'::timestamp  
and (
select coalesce(sum(receipt_value), 0)
from table1 
where 
receipt_customer_id = t.receipt_customer_id and
-- Transacted in July
receipt_date >= '2020-07-01'::timestamp and
receipt_date < '2020-08-01'::timestamp      
)  = 0
group by receipt_customer_id;

或者如果你只想要客户数量和receipt_value:的总和

Select
count(distinct receipt_customer_id), sum(receipt_value)
From
table1 t
where
-- Transacted in August
t.receipt_date >= '2020-08-01'::timestamp and 
t.receipt_date < '2020-09-01'::timestamp  
and (
select coalesce(sum(receipt_value), 0)
from table1 
where 
receipt_customer_id = t.receipt_customer_id and
-- Transacted in July
receipt_date >= '2020-07-01'::timestamp and
receipt_date < '2020-08-01'::timestamp      
)  = 0

请参阅这个数据库fiddle来测试它(如果你想问后续问题,请随时使用它(。注意,如果你想重新引入current_date,你可以这样做(但你可能想计算月初的日期_trunc可以帮助你(。

相关内容

最新更新