【问题标题】:Where clause on date, hour & minute日期、小时和分钟的 Where 子句
【发布时间】:2021-08-19 06:43:43
【问题描述】:

我有一张桌子。

userId|date      |hour|minute|five|four|three|two|one|
------+----------+----+------+----+----+-----+---+---+
dinesh|2021-05-28|   6|     5|   0|   1|    0|  0|  0|
jay   |2021-05-29|   1|    20|   1|   0|    1|  0|  0|

如何过滤给定范围内的日期、小时和分钟。 假设我想要从 2021-05-28 05:00 到 2021-05-29 23:59 的所有条目

我将执行一些聚合查询,例如

select userId, date, sum(five) as five, sum(four) as four
from table where <2021-05-28 05:00 to 2021-05-29 23:59> group by userId, date

【问题讨论】:

  • 如果您将日期和时间存储在 timestamp 类型而不是三个单独的列中,这将变得更加容易。
  • 这是一个按分钟聚合的表格。如果我按时间戳存储,那么它将是我们不想要的秒
  • date 列的数据类型是什么?是日期还是字符串?
  • 现在是日期,我们也可以把它改成字符串。它是一个柱状数据库。
  • @DineshGowda 您可以将四舍五入的分钟存储为时间戳类型,无需几秒钟即可参与。

标签: sql postgresql datetime google-bigquery where-clause


【解决方案1】:

由于您实际上是在存储时间戳并尝试使用它进行时间戳操作,因此我建议使用 timestamp 类型。您的数据将如下所示:

 userid |      timestamp      | five | four | three | two | one
--------+---------------------+------+------+-------+-----+-----
 dinesh | 2021-05-28 06:05:00 |    0 |    1 |     0 |   0 |   0
 jay    | 2021-05-29 01:20:00 |    1 |    0 |     1 |   0 |   0

你可以这样查询:

select userId, timestamp::date, sum(five) as five, sum(four) as four
from your_table
where timestamp between '2021-05-28 05:00:00' and '2021-05-29 23:59:59'
group by userId, timestamp::date

【讨论】:

  • 我如何在基表中的时间戳字段上四舍五入到最接近的分钟?
  • 我不完全确定您的意思,但是有一个 date_trunc 函数可以截断您不关心的所有秒数:postgresql.org/docs/13/…
【解决方案2】:

考虑下面的 BigQuery 标准 SQL(假设 date 列是日期数据类型)

select userId, date, sum(five) as five, sum(four) as four
from your_table
where datetime(date, time(hour, minute, 0)) 
between datetime('2021-05-28 05:00:00') and datetime('2021-05-29 23:59:59')
group by userId, date

【讨论】:

  • 只是好奇如果日期是字符串类型的答案是什么?
  • 你可以改用where datetime(parse_date('%F', date), time(hour, minute, 0)) between ...
猜你喜欢
  • 1970-01-01
  • 2023-03-21
  • 2018-04-30
  • 1970-01-01
  • 2010-12-29
  • 2012-01-02
  • 2017-09-25
  • 1970-01-01
  • 2021-12-27
相关资源
最近更新 更多