在下面的示例中,确定何时对日期使用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;
但正确答案如下,我不明白为什么我们需要在这里使用date_trunc函数,因为查询可以运行没有它
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;
1条答案
按热度按时间kmynzznz1#
1-
WHERE stocking_date>'2018-10-01'
和2-WHERE DATE_TRUNC('month', stocking_date) > '2018-10-01'
的区别是:第一个将显示日期为2018-10-02的记录,因此将有2018年10月的记录,而提交则表示仅保留2018年10月之后的记录。
使用DATE_TRUNC的第二个函数将把任何日期转换为该月的第一天。例如2018-10-15将是2018-10-01,2018-10-30也将是2018-10-01。当条件> '2018-10-01'时,十月份的所有日期都不会显示在结果中。