oldest =
      now_tz()
      |> ensure_utc()
      |> truncate_day()
      |> add_days(-1 * days)

    subquery =
      from v in Gas,
        select: %{
          value: v.value,
          read_on: v.read_on,
          read_on_tz: fragment("(? AT TIME ZONE 'UTC')", v.read_on)
        },
        where: v.read_on >= ^oldest

    query =
      from v in subquery(subquery),
        select: %{
          read_on_hour:
            fragment(
              "date_trunc('hour', ?) + date_part('minute', ?)::int / 30 * interval '30 min' as read_on_hour",
              v.read_on_tz,
              v.read_on_tz
            ),
          max: fragment("max(?)", v.value),
          min: fragment("min(?)", v.value)
        },
        group_by: fragment("read_on_hour"),
        order_by: fragment("read_on_hour desc")