固定SQL中每个uuid的时间戳范围

时间:2019-03-28 12:50:43

标签: postgresql

我想用最近n周的数据时间戳(在本例中为n = 3)和所有数据生成一个表,即使它为空。

我正在使用以下代码

   with raw_weekly_data as (SELECT
   distinct d.uuid,
   date_trunc('week',a.start_timestamp) as tstamp,
   avg(price) as price
   FROM
   a join d on a.uuid = d.uuid
   where start_timestamp between date_trunc('week',now()) -           interval '3 week' and date_trunc('week',now())
   group by 1,2,3
   order by 1)

   ,tstamp as (SELECT
   distinct tstamp
   FROM
   raw_weekly_data
   )

   SELECT
   t.tstamp,
   r.*
   from raw_weekly_data r right join tstamp t on r.tstamp =       t.tstamp
   order by uuid

我想要这样的东西:

week  |  uuid  | price
w1    |  1     | 10
w2    |  1     | 2
w3    |  1     |
w1    |  2     | 20
w2    |  2     |
w3    |  2     |
w1    |  3     | 10
w2    |  3     | 10
w3    |  3     | 20

但是,不会显示所有空结果。这里最好的方法是什么?

week  |  uuid  | price
w1    |  1     | 10
w2    |  1     | 2
w1    |  2     | 20
w1    |  3     | 10
w2    |  3     | 10
w3    |  3     | 20

1 个答案:

答案 0 :(得分:0)

形成所有UUID的笛卡尔积,然后 LEFT JOIN到实际平均价格,即每(week, uuid)的价格。喜欢:

SELECT *
FROM   generate_series (date_trunc('week', now() - interval '3 week')
                                         , now() - interval '1 week'
                      , interval '1 week') tstamp
CROSS  JOIN (SELECT DISTINCT uuid FROM a) a
LEFT   JOIN (
   SELECT d.uuid
        , date_trunc('week', a.start_timestamp) AS tstamp
        , avg(price) AS price  -- d.price?
   FROM   a
   JOIN   d USING (uuid)
   WHERE  a.start_timestamp >= date_trunc('week',now()) - interval '3 week'
   AND    a.start_timestamp <  date_trunc('week',now())
   ) ad USING (uuid, tstamp)
GROUP  BY 1, 2
ORDER  BY 1, 2

通过这种方式,您可以获得过去三周的所有所有组合和UUID,并以平均价格进行扩展-如果该组合应存在的话。
根据一些有根据的猜测来填写缺少的信息..