在SQL中选择时间戳范围

时间:2018-03-22 02:33:21

标签: sql postgresql timestamp

我正在尝试在SQL postgres中选择特定日期范围内的特定时间范围。请看下面的代码,它在'10:00:00'给出错误。 每列的数据类型是: “余额”的数字, 字符变化(255)为“货币”, “created_at”没有时区的时间戳(例如:2018-03-20 00:00:00)。

我尝试了此链接但没有成功。 MySQL select based on daily timestamp range

SELECT SUM(bl.balance) AS balance, bl.currency, bl.created_at
  FROM balance_logs bl
  WHERE bl.balance_scope = 'system' AND
        created_at >= CURRENT_DATE - 2 AND
        created_at < CURRENT_DATE AND
        created_at BETWEEN '10:00:00' AND '11:00:00'
  GROUP BY bl.currency, bl.created_at
  ORDER BY created_at DESC

1 个答案:

答案 0 :(得分:1)

比较需要时间:

SELECT SUM(bl.balance) AS balance, bl.currency, bl.created_at
FROM balance_logs bl
WHERE bl.balance_scope = 'system' AND
      created_at >= CURRENT_DATE - 2 AND
      created_at < CURRENT_DATE AND
      created_at::time BETWEEN '10:00:00'::time AND '11:00:00'::time
GROUP BY bl.currency, bl.created_at
ORDER BY created_at DESC;

但是,我认为最好将WHERE条件写为:

      extract(hour from created_at) = 10