【问题标题】:sql / postgresql - counting value increase within month rangesql / postgresql - 月份范围内的计数值增加
【发布时间】:2021-08-05 00:15:00
【问题描述】:

下面的表格名为tbl

| id | json     | date                |
| -- | -------- | ------------------- |
| 1  | {"id":1} | 2021-01-01 00:00:00 |
| 1  | {"id":1} | 2021-09-02 00:00:00 |
| 1  | {"id":1} | 2021-09-03 00:00:00 |
| 3  | {"id":3} | 2021-09-03 00:00:00 |
| 4  | {"id":4} | 2021-09-01 00:00:00 |
| 4  | {"id":4} | 2021-09-02 00:00:00 |
| 5  | {"id":5} | 2021-01-01 00:00:00 |
| 5  | {"id":5} | 2021-09-01 00:00:00 |
| 5  | {"id":5} | 2021-09-02 00:00:00 |
| 5  | {"id":5} | 2021-09-01 00:00:00 |
| 5  | {"id":5} | 2021-09-03 00:00:00 |
| 5  | {"id":5} | 2021-09-04 00:00:00 |

在这里,我需要获取 1 月到 9 月之间发生的值增加。如果 id 在 both 一月和九月都没有条目,那么我们将忽略它,因为我们只想包含月份之间的变化。出于我们的目的,我们不需要显示带有负面变化的 id。

我正在寻找如下输出,

| id | json     | change |
| -- | -------- | ------ |
| 1  | {"id":1} | 1      |
| 5  | {"id":5} | 4      |

以下是我目前有的一个查询,但不清楚如何计算每月值...

with id as (
    select json_array_elements(json->'id')
    from tbl
),
date as (
    select date
    from tbl
)
select *
from id, date;

【问题讨论】:

    标签: sql json postgresql


    【解决方案1】:

    这里有一个两步解决方案:首先计算每个 ID 在 1 月和 9 月的出现次数,然后减去并过滤掉不需要的行。我跳过了 json,因为它只是重复了 ID 中的信息。

    WITH counts AS (
      SELECT 
        id, 
        count(*) FILTER (WHERE date_trunc('month', date) = '2021-09-01 00:00:00') as sept_occurrences, 
        count(*) FILTER (WHERE date_trunc('month', date) = '2021-01-01 00:00:00') as jan_occurrences 
      FROM tbl 
      GROUP BY id
    ) 
    SELECT id, sept_occurrences - jan_occurrences as change
    FROM counts
    WHERE sept_occurrences > 0
    AND jan_occurrences > 0;
    
     id | change
    ----+--------
      5 |      4
      1 |      1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-03
      • 1970-01-01
      • 2017-10-09
      相关资源
      最近更新 更多