You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DATE_TRUNC函数适用场景解析:为何SQL查询WHERE子句需使用它

DATE_TRUNC在日期筛选场景中的作用解析

先看你的查询代码和正确答案的核心差异:

你的查询代码

SELECT
  -- Select eatery and calculate total cost
  eatery,
  DATE_TRUNC('month', stocking_date) :: DATE AS delivr_month,
  sum(meal_cost) :: FLOAT AS cost
FROM meals
JOIN stock ON meals.meal_id = stock.meal_id
-- Keep only the records after October 2018
WHERE stocking_date>'2018-10-01'
GROUP BY eatery, delivr_month
ORDER BY eatery, delivr_month; 

正确答案代码

SELECT
  -- Select eatery and calculate total cost
  eatery,
  DATE_TRUNC('month', stocking_date) :: DATE AS delivr_month,
  SUM(meal_cost * stocked_quantity) :: FLOAT AS cost
FROM meals
JOIN stock ON meals.meal_id = stock.meal_id
-- Keep only the records after October 2018
WHERE DATE_TRUNC('month', stocking_date) > '2018-10-01'
GROUP BY eatery, delivr_month
ORDER BY eatery, delivr_month;

为什么WHERE子句需要用DATE_TRUNC?

核心原因是需求是“2018年10月之后”的数据,也就是完全排除10月的所有记录,两者的筛选逻辑有本质区别:

  • 直接用stocking_date > '2018-10-01':会保留所有2018-10-01当天及之后的记录,包括10月整月(比如2018-10-02、2018-10-31的记录都会被包含),这不符合“10月之后”的要求。
  • 用DATE_TRUNC('month', stocking_date) > '2018-10-01':DATE_TRUNC会把任意日期截断到当月第一天,比如2018-10-31会被转为2018-10-01,2018-11-01转为2018-11-01。这个条件会筛选出所有月份起始日期晚于2018-10-01的记录,也就是从11月开始的所有数据,精准排除了10月的全部记录,完全匹配需求。

另外补充一个细节:正确答案里的SUM(meal_cost * stocked_quantity)才是正确的成本计算逻辑——餐品成本应该是单价×进货数量,你原来的sum(meal_cost)只是把单价累加,结果是错误的。

内容的提问来源于stack exchange,提问作者Chloe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 14:32:52