【问题标题】:How to DRY up a PostgreSQL query如何干掉一个 PostgreSQL 查询
【发布时间】:2020-10-01 23:18:47
【问题描述】:

我不经常编写原始 SQL,但最近在这样做时,我不禁认为这个查询不是很干燥。有办法收紧吗?

SELECT
  COUNT(*) as "Users", DATE_TRUNC('day', created_at) AS "Date"
FROM
  users
WHERE created_at > now() - interval '1 year'
GROUP BY DATE_TRUNC('day', created_at)
ORDER BY DATE_TRUNC('day', created_at);

目前返回:

Users  Date
175    2019-10-01 00:00:00
54     2019-10-02 00:00:00
142    2019-10-03 00:00:00
...

我想要的是按created_at 日期对所有新用户进行分组,但只能追溯到一年(或我们选择的任意日期)。不确定DATE_TRUNC 是解决此问题的最佳方法。更确定重复3次可能不是。

【问题讨论】:

    标签: sql postgresql datetime count sql-order-by


    【解决方案1】:

    您可以在group byorder by 中使用列别名。

    SELECT
      count(*) as "Users",
      date_trunc('day', created_at) AS "Date"
    FROM
      users
    WHERE
      created_at > now() - interval '1 year'
    GROUP BY "Date"
    ORDER BY "Date"
    

    【讨论】:

      【解决方案2】:

      date_trunc() 是将时间戳截断为日期的正确工具。另一种方法是投射。至于group byorder by 子句,可以使用位置参数或列别名。

      所以:

      SELECT COUNT(*) as cnt_users, created_at::date AS created_date
      FROM users
      WHERE created_at > current_date - interval '1 year'
      GROUP BY created_date  -- or ORDER BY 2
      ORDER BY created_date  -- or ORDER BY 2
      

      注意事项:

      • 我调整了where 子句,使其在整个天过滤

      • 我使用了不带引号的标识符;引用标识符并不是 DRY 开始的,它也使它们区分大小写

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-11
        • 1970-01-01
        • 1970-01-01
        • 2021-01-27
        • 1970-01-01
        相关资源
        最近更新 更多