【问题标题】:PostgreSQL: How to query for the last day of the current month?PostgreSQL:如何查询当月的最后一天?
【发布时间】:2023-03-11 05:30:01
【问题描述】:

我想以数字格式返回当前月份的最后一天。我将如何在 Postgres 中编写 SQL 查询来实现这一点?

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:
    SELECT
      TO_CHAR(
        DATE_TRUNC('month', CURRENT_DATE)  -- first day of current month
          + INTERVAL '1 month'             -- first day of next month
          - INTERVAL '1 day',              -- last day of current month
        'DD'                               -- format last day of month
      ) last_day_of_month
    

    【讨论】:

    • 或者如果你想要一个整数值只是extract(day from ...)而不是to_char
    • “1 个月 - 1 天”也可以
    【解决方案2】:

    使用一个

    LEFT OUTER JOIN sales_registrations FROM months

    (而不是您的右连接)。这样,您将从 sales_registrations 中获取没有连接的记录,并且所有这些字段都将具有 NULL 值。

    如果您不想在结果中看到 NULLS, 使用 SUMCASE

    SUM(CASE WHEN some_field_from_sales_registrations IS NOT NULL THEN 1 ELSE 0 END) as c

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 2012-02-15
      • 1970-01-01
      • 2016-02-22
      相关资源
      最近更新 更多