如何构建SQL以按日期获取分组数据

问题描述 投票:2回答:2

我在Postgres DataBase中有这样的数据

 | id |  name  |    start_date       |      end_date       |
   1    Event1  2018-09-14 14:22:00     2018-09-15 14:22:00
   2    Event2  2018-09-15 14:22:00     2018-09-15 15:22:00

我需要SQL返回我的响应group_by日期和如果事件持续时间(end_date,start_date)花了2天我需要在两天内返回他两次数组,这一切都应按日期排序。所以响应应该是这样的。

{
  "2018-09-14": [
      {
        "id": 1,
        "name": "Event1",
        "start_date": "2018-09-14 14:22:00",
        "end_date": "2018-09-15 14:22:00",
    }],
    "2018-09-15": [{
        "id": 1,
        "name": "Event1",
        "start_date": "2018-09-14 14:22:00",
        "end_date": "2018-09-15 14:22:00",
    },
    {
        "id": 2,
        "name": "Event2",
        "start_date": "2018-09-15 14:22:00",
        "end_date": "2018-09-15 15:22:00",
    }]
 }

你能帮帮我这个SQL吗?

sql json postgresql
2个回答
1
投票

demo: db<>fiddle

SELECT 
    jsonb_object_agg(dates, data_array)
FROM (
    SELECT
        dates,
        jsonb_agg(data) as data_array
    FROM (
        SELECT DISTINCT
            unnest(ARRAY[start_date::date, end_date::date]) as dates,
            row_to_json(events)::jsonb as data
        FROM
            events
    )s
    GROUP BY dates
) s
  1. 使用row_to_json将表转换为json对象。
  2. 使用ARRAY[]将两个日期聚合到一个数组中
  3. unnest()在每个日期扩展数据。

到目前为止的结果:

dates        data
2018-09-14   {"id": 1, "name": "Event1", "end_date": "2018-09-15 14:22:00", "start_date": "2018-09-14 14:22:00"}
2018-09-15   {"id": 1, "name": "Event1", "end_date": "2018-09-15 14:22:00", "start_date": "2018-09-14 14:22:00"}
2018-09-15   {"id": 2, "name": "Event2", "end_date": "2018-09-15 15:22:00", "start_date": "2018-09-15 14:22:00"}
2018-09-15   {"id": 2, "name": "Event2", "end_date": "2018-09-15 15:22:00", "start_date": "2018-09-15 14:22:00"}
  1. DISTINCT消除了start_date == end_date所有绑定的元素。
  2. 按日期分组,将json元素聚合成json数组(jsonb_agg
  3. 毕竟,用jsonb_object_aggkey == date将表分组为json元素(value == json array

1
投票

如果您只想要行,则只需要以下步骤:

  1. 使用ARRAY[]将两个日期聚合到一个数组中
  2. unnest()在每个日期扩展数据。
  3. DISTINCT消除了start_date == end_date所有绑定的元素。

查询:

SELECT DISTINCT
    unnest(ARRAY[start_date::date, end_date::date]) as dates,
    *
FROM
    events

结果:

dates        id   name     start_date            end_date
2018-09-14   1    Event1   2018-09-14 14:22:00   2018-09-15 14:22:00
2018-09-15   1    Event1   2018-09-14 14:22:00   2018-09-15 14:22:00
2018-09-15   2    Event2   2018-09-15 14:22:00   2018-09-15 15:22:00

demo:db<>fiddle

© www.soinside.com 2019 - 2024. All rights reserved.