具有已删除属性的历史记录表的累计计数

时间:2018-05-04 07:32:17

标签: postgresql count

我有一个记录更新的历史记录表,我想计算可以添加或删除值的累计总数。 (即一个月的累计总数可能比前一个少)。

例如,这是一个表格,其中包含人员记录标签更新的历史记录。 (id是人员记录的ID)。

我想知道在任何一个月内有多少人拥有“已建立”的标签,这是在上个月添加或删除它的时间。

+----+------------------------+---------------------+
| id |          tags          |     created_at      |
+----+------------------------+---------------------+
|  1 | ["vip", "established"] | 2017-01-01 00:00:00 |
|  2 | ["established"]        | 2017-01-01 00:00:00 |
|  3 | ["established"]        | 2017-02-01 00:00:00 |
|  1 | ["vip"]                | 2017-03-01 00:00:00 |
|  4 | ["established"]        | 2017-05-01 00:00:00 |
+----+------------------------+---------------------+

these posts的帮助下,我已经走到了这一步:

SELECT 
  item_month,
  sum(count(distinct(id))) OVER (ORDER BY item_month)
FROM (
  SELECT 
    to_char("created_at", 'yyyy-mm') as item_month,
    id
  FROM person_history 
  WHERE tags ? 'established'
) t1
GROUP BY item_month;

这给了我:

month   count
2017-01 2
2017-02 3
2017-05 4 <--- should be 3

而且它也错过了2017-03的一个条目,应该是2.

(对于2017-04的条目也会很好,但如果需要,UI可以始终从上个月推断出来)

1 个答案:

答案 0 :(得分:2)

以下是分步教程,您可以尝试折叠所有这些CTE:

with 
  -- Example data
  person_history(id, tags, created_at) as (values
    (1, '["vip", "est"]'::jsonb, '2017-01-01'::timestamp),
    (2, '["est"]', '2017-01-01'), -- Note that Person 2 changed its tags several times per month 
    (2, '["vip"]', '2017-01-02'),
    (2, '["vip", "est"]', '2017-01-03'),
    (3, '["est"]', '2017-02-01'),
    (1, '["vip"]', '2017-03-01'),
    (4, '["est"]', '2017-05-01')),
  -- Get the last tags for each person per month
  monthly as (
    select distinct on (id, date_trunc('month', created_at))
      id,
      date_trunc('month', created_at) as month,
      tags,
      created_at
    from person_history
    order by 1, 2, created_at desc),
  -- Retrieve tags from previous month
  monthly_prev as (
    select
      *,
      coalesce((lag(tags) over (partition by id order by month)), '[]') as prev_tags
    from monthly),
  -- Calculate delta: if "est" was added then 1, removed then -1, nothing heppens then 0
  monthly_delta as (
    select
      *,
      case
        when tags ? 'est' and not prev_tags ? 'est' then 1
        when not tags ? 'est' and prev_tags ? 'est' then -1
        else 0
      end as delta
    from monthly_prev),
  -- Sum all deltas for each month
  monthly_total as (
    select month, sum(delta) as total
    from monthly_delta
    group by month)
-- Finally calculate cumulative sum
select *, sum(total) over (order by month) from monthly_total
order by month;

结果:

┌─────────────────────┬───────┬─────┐
│        month        │ total │ sum │
├─────────────────────┼───────┼─────┤
│ 2017-01-01 00:00:00 │     2 │   2 │
│ 2017-02-01 00:00:00 │     1 │   3 │
│ 2017-03-01 00:00:00 │    -1 │   2 │
│ 2017-05-01 00:00:00 │     1 │   3 │
└─────────────────────┴───────┴─────┘