[英]Redshift: Add Row for each hour in a day
I have a table contains item_wise quantity at different hour of date.我有一张表包含日期不同时间的 item_wise 数量。 trying to add data for each hour(24 enteries in a day) with previous hour available quantity.
尝试使用前一小时的可用数量添加每小时(一天 24 个条目)的数据。 For example for hour(2-10), it will be 5.
例如小时(2-10),它将是 5。
How can i add previous available entry.我如何添加以前的可用条目。 Need suggestion
需要建议
item_id| date | hour| quantity
101 | 2022-04-25 | 2 | 5
101 | 2022-04-25 | 10 | 13
101 | 2022-04-25 | 18 | 67
101 | 2022-04-25 | 23 | 27
You can try to use generate_series
to generate hours number, let it be the OUTER JOIN
base table,您可以尝试使用
generate_series
生成小时数,让它成为OUTER JOIN
基表,
Then use a correlated-subquery to get your expect quantity
column然后使用相关子查询来获取您的预期
quantity
列
SELECT t1.*,
(SELECT quantity
FROM T tt
WHERE t1.item_id = tt.item_id
AND t1.date = tt.date
AND t1.hour >= tt.hour
ORDER BY tt.hour desc
LIMIT 1) quantity
FROM (
SELECT DISTINCT item_id,date,v.hour
FROM generate_series(1,24) v(hour)
CROSS JOIN T
) t1
ORDER BY t1.hour
Provided the table of int 1.. 24 is all24(hour)
you can use lead
and join
如果 int 1.. 24 的表是
all24(hour)
你可以使用lead
和join
select t.item_id, t.date, all24.hour, t.quantity
from all24
join (
select *,
lead(hour, 1, 25) over(partition by item_id, date order by hour) - 1 nxt_h
from tbl
) t on all24.hour between t.hour and t.nxt_h
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.