time_bucket 和 date_trunc 的问题或可解释的差异?

Problem with time_bucket and date_trunc or explainable difference?

我有两个行为截然不同的不同查询,但我认为它们应该相同。 第一个给了我我想要的,第二个没有。你能解释一下吗?

    with base as (
    select time at time zone 'utc' as t, value as kw
    from metrics
    where site = 'IIHS-Phase2'
      and measurement = 'kw'
      and equipment = 'WattNode'
      and time at time zone 'utc' > '2020-04-1 00:00'
      and time at time zone 'utc' < '2020-05-01 00:00'
      and value > 0),
 quarter as (
         select time_bucket('15min', t) t2, avg(kw) kw
         from base
         group by 1
     )
select date_trunc('day', t2), sum(kw) * .25 kwh
from quarter
group by 1
order by 1

这会产生预期的输出:

2020-04-03 00:00:00.000000,47.74750179624
2020-04-04 00:00:00.000000,763.0610862812115
2020-04-05 00:00:00.000000,809.9363199208758
2020-04-06 00:00:00.000000,806.3479266995703
2020-04-07 00:00:00.000000,789.4193852521148
2020-04-08 00:00:00.000000,965.5504895999275
2020-04-09 00:00:00.000000,852.1921420684275
2020-04-10 00:00:00.000000,744.5305964113129
2020-04-11 00:00:00.000000,779.511450610154

其他查询:

with quarter as (
    select time_bucket('15min', time at time zone 'utc') as localtime, avg(value) * .25 as kwh
    from metrics
    where site = 'IIHS-Phase2'
      and measurement = 'kw'
      and equipment = 'WattNode'
      and time at time zone 'utc' > '2020-04-1 00:00'
      and time at time zone 'utc' < '2020-05-01 00:00'
      and value > 0
    group by 1)
select date_trunc('day', localtime), sum(kwh)
from quarter

给出完全不同的输出:

0 years 0 mons 0 days 0 hours 0 mins 0.00 secs,22946.408690298373

我错过了什么?

您在第二个查询中似乎没有分组依据?

您的第二个查询在其周围使用 keyword localtime, which returns current time without timezone. I guess this is the issue. I suggest either to use double quotes,即 "localtime",或者使用其他名称作为标识符。

UDPATE:正如 davidk 的另一个回复中提到的,您也缺少 group by。