【问题标题】:Count Unique Data With Minimum Date Postgres使用最小日期 Postgres 计算唯一数据
【发布时间】:2022-01-16 19:17:38
【问题描述】:

我在尝试计算表中的数据时遇到问题。

例如我的桌子是这样的:

table = test
id       | transaction_date
1        | '2021-10-01 00:00:00'
2        | '2021-10-01 00:00:00'
3        | '2021-10-02 00:00:00'
4        | '2021-10-03 00:00:00'
5        | '2021-10-04 00:00:00'
6        | '2021-10-05 00:00:00'
7        | '2021-10-06 00:00:00'

1        | '2021-11-01 00:00:00'
2        | '2021-11-01 00:00:00'
3        | '2021-11-02 00:00:00'

1        | '2021-12-01 00:00:00'
2        | '2021-12-01 00:00:00'
3        | '2021-12-02 00:00:00'
4        | '2021-12-03 00:00:00'
8        | '2021-12-04 00:00:00'
8        | '2021-12-05 00:00:00'
9        | '2021-12-06 00:00:00'
9        | '2021-12-07 00:00:00'

我尝试使用此查询

WITH first_transaction_AS (SELECT MIN(transaction_date), id FROM test),
previous_month AS (SELECT DISTINCT idFROM test 
WHERE transaction_date >= date_trunc('month', transaction_date)-interval '1 month' 
AND transaction_date < date_trunc('month', transaction_date)

-- WHERE clause for previous month will be dynamic

SELECT date_trunc('month', transaction_date), COUNT(DISTINCT id)
FROM test 
WHERE test.id NOT IN (SELECT id FROM previous_month) AND transaction_date NOT IN (SELECT min FROM first_transaction)

我想实现一个聚合查询,其中: 计算 ID 其中 ID 本月有交易且 ID 上个月无交易且不是 ID 的第一次交易

目前的问题是,ID 8 和 9 仍然会被计算在内,因为他们在同月的第一笔交易之后还有一笔交易。

所以我的目标是:

    Date                    |         Count
  2021-12-01 00:00:00       |           1  (4)

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    根据规则只有 1 个。

    select 
      date(date_trunc('month', transaction_date)) as "Date"
    , count(distinct id) as "Count"
    from test t
    where transaction_date >= date_trunc('month', current_date)
      and transaction_date < (date_trunc('month', current_date)+interval '1 month') 
      and not exists ( -- not previous month
          select 1
          from test t2
          where t2.id = t.id
            and t2.transaction_date >= date_trunc('month', current_date) - interval '1 month'
            and t2.transaction_date <  date_trunc('month', current_date)
      
      )
      and exists ( -- created previously
          select 1
          from test t2
          where t2.id = t.id
            and t2.transaction_date <  date_trunc('month', current_date)
      )
    group by date_trunc('month', transaction_date)
      
      
    
    日期 |数数 :--------- | ----: 2021-12-01 | 1

    dbfiddle here

    上的演示

    【讨论】:

    • 获得它的好方法。但如果我尝试使用更多数据,它会给我超时。除了使用自加入方法之外还有其他方法吗?谢谢
    • @YohanesLim 可以检查查询的解释。也许需要一个索引?但我已经改变了小提琴。使用临时表的地方还有很多。基本上切断了逻辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-12-16
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-02
    相关资源
    最近更新 更多