【问题标题】:(MySQL) Having trouble with a DATEDIFF function(MySQL) 使用 DATEDIFF 函数时遇到问题
【发布时间】:2020-02-10 02:34:24
【问题描述】:

我在最后一列中遇到了一些问题,即提供电影租借的第一个日期和最后一个日期之间的天数。

我的导师正确输出

我的输出不正确。我的 days_between_first_and_last_rent 中的一些输出比我的导师输出高 1 天:

出租桌

DATEDIFF 位于底部 FROM 子句的正上方


-- NOW()'Jordan_Rasmussen' just shows my name in the output for my teacher
-- Get a list of film titles
SELECT NOW()'Jordan_Rasmussen',
f.title,

( -- Get the count of the inventory 
    SELECT COUNT(i2.inventory_id)
    FROM inventory AS i2 
    WHERE i2.film_id = f.film_id 
    ) AS inventory_count,

-- Get the count of the number of times a movie was rented 
COUNT(r.rental_id) AS num_times_rented,

-- Determine the demand of the film by the number of times it was rented
-- If the film has no inventory, then its demand is 'no inventory' 
CASE
WHEN COUNT(i.inventory_id) = 0  THEN 'No Inventory'
WHEN COUNT(r.rental_id) > 20 THEN 'Fire'
WHEN COUNT(r.rental_id) > 10 THEN 'Hot'
WHEN COUNT(r.rental_id) > 5 THEN 'Warm'
ELSE 'Flop'
END AS demand,

-- Get the date of the first time the movie was rented
MIN(DATE(r.rental_date)) AS first_date_rented,

-- Get the number of days between the first and last day the movie was rented
DATEDIFF(MAX(DATE(r.rental_date)),MIN(DATE(r.rental_date))) AS days_between_first_and_last_rent

FROM film AS f 
LEFT JOIN inventory AS i ON f.film_id = i.film_id 
LEFT JOIN rental AS r ON i.inventory_id = r.inventory_id

GROUP BY f.title
ORDER BY f.title 

我只是不确定为什么我会为某些行而不是所有行获得 +1。

【问题讨论】:

  • 感谢保罗的编辑!这样看起来好多了。
  • 提供一些示例数据作为小提琴。
  • 附带说明:您可以将inventory_count 子查询替换为COUNT DISTINCT i.inventory_id) AS inventory_count
  • 另一个站点注释:单引号用于字符串文字。在标准 SQL 中为名称使用双引号:SELECT NOW() AS "Jordan_Rasmussen", ....

标签: mysql sql phpmyadmin datediff


【解决方案1】:

您的查询看起来不错。我想您的老师只是没有将日期时间缩短为日期,因此从'2020-01-15 10:00:00''2020-01-16 09:00:00' 的租用期对他们来说比直到'2020-01-16 11:00:00' 少一天。

这可以解释您所看到的一日差异。

【讨论】:

  • 看起来你是对的,当我执行 TIMESTAMPDIFF() 而不是 DATEDIFF 时,我得到了正确的输出。正如你提到的,我可能不应该将日期减少到没有时间戳的日期。
【解决方案2】:

我能得到和我的导师一样的输出

DATEDIFF(MAX(DATE(r.rental_date)),MIN(DATE(r.rental_date))) AS days_between_first_and_last_rent

然后用

替换
TIMESTAMPDIFF(DAY,MIN(r.rental_id),MAX(r.rental_id) AS days_between_first_and_last_rent. 

我应该使用 TIMESTAMPDIFF() 而不是 DATEDIFF()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 2015-07-17
    • 1970-01-01
    • 2012-09-21
    相关资源
    最近更新 更多