我想通过比较postgresql中的两列得到一个具体的答案
我有这样一个问题:我想通过比较postgresql中的两列得到一个具体的答案,sql,postgresql,Sql,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'
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
Sum: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;
或者,如果您只需要客户数量和收据价值之和:
看看这个测试,如果你想问后续问题,请随意使用。请注意,如果您想重新引入当前日期,您可以这样做,但您可能希望计算月初,这会有所帮助。示例数据会有所帮助。
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;
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