【发布时间】:2023-03-11 05:30:01
【问题描述】:
我想以数字格式返回当前月份的最后一天。我将如何在 Postgres 中编写 SQL 查询来实现这一点?
【问题讨论】:
标签: sql postgresql
我想以数字格式返回当前月份的最后一天。我将如何在 Postgres 中编写 SQL 查询来实现这一点?
【问题讨论】:
标签: sql postgresql
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。
使用一个
LEFT OUTER JOIN sales_registrations FROM months
(而不是您的右连接)。这样,您将从 sales_registrations 中获取没有连接的记录,并且所有这些字段都将具有 NULL 值。
如果您不想在结果中看到 NULLS,
使用 SUM 和 CASE :
SUM(CASE WHEN some_field_from_sales_registrations IS NOT NULL THEN 1 ELSE 0 END) as c
【讨论】: