【问题标题】:Fill empty missing dates in result from raw sql query在原始 sql 查询的结果中填充空的缺失日期
【发布时间】:2020-06-16 04:28:30
【问题描述】:

我有一个类似以下的查询,需要 min_datemax_date

Select TO_CHAR(date_trunc('hour', table.date), 'YYYY-MM-DD HH24:00') as formatted_date,
count(DISTINCT table.order_id) as unique_orders, sum(table.price) as total_price from table
where table.date>=min_date and table.date<=max_date

result = ActiveRecord::Base.connection.execute(query).values.to_a

这将为我提供订单计数和每“小时”的总价格。例如,说这是我的桌子

<id: 1, order_id: 1, date: 2020-06-10 10:18:01+00, price:10>
<id: 2, order_id: 1, date: 2020-06-10 10:43:19+00, price:14>
<id: 3, order_id: 2, date: 2020-06-10 12:10:00+00, price:15>
<id: 4, order_id: 3, date: 2020-06-10 12:20:21+00, price:10>
<id: 5, order_id: 3, date: 2020-06-10 14:10:54+00, price:20>

还有我的min_date = 2020-06-10 09:00:00+00max_date = 2020-06-10 14:00:00+00。这将是我的结果:

[[2020-06-10 10:00, 1, 24], [2020-06-10 12:00, 2, 25], [2020-06-10 14:00, 1, 20]]

我希望像这样包含 min_date 和 max_date 之间的缺失时间:

[[2020-06-10 09:00, 0, 0], [2020-06-10 10:00, 1, 24], [2020-06-10 11:00, 0, 0], [2020-06-10 12:00, 2, 25], [2020-06-10 13:00, 0, 0] [2020-06-10 14:00, 1, 20]]

所以我还想要表中不存在但包含在 min_date 和 max_date 之间的时间范围内的所有时间。在这种情况下,这是我想要的所有时间,但可能是所有“周”或“月”,具体取决于我传递给 date_trunc 的参数。

【问题讨论】:

  • RIGHT JOINgenerate_series 函数调用的结果。

标签: sql ruby-on-rails postgresql


【解决方案1】:

使用generate_series() 计算您想要的所有日期。然后使用left join 引入数据:

select to_char(gs.dte, 'YYYY-MM-DD HH24:00') as formatted_date,
       count(distinct t.order_id) as unique_orders, sum(t.price) as total_price
from generate_series(min_date, max_date, interval '1 hour') gs(dte) left join
     table t
     on t.date >= gs.dte and
        t.date < gs.dte + interval '1 hour' and table.date<=max_date
group by gs.dte
order by gs.dte;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-09
    • 2019-07-20
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多