gpt4 book ai didi

MySQL:为什么日期差异总是0?

转载 作者:行者123 更新时间:2023-11-30 22:07:03 28 4
gpt4 key购买 nike

我正在练习我的 SQL 技能,这是我正在练习的一个问题: https://www.hackerrank.com/challenges/projects

问题是:

You are given a table, Projects, containing three columns: Task_ID, Start_Date and End_Date. It is guaranteed that the difference between the End_Date and the Start_Date is equal to 1 day for each row in the table. If the End_Date of the tasks are consecutive, then they are part of the same project. Samantha is interested in finding the total number of different projects completed.

Write a query to output the start and end dates of projects listed by the number of days it took to complete the project in ascending order. If there is more than one project that have the same number of completion days, then order by the start date of the project.

我的逻辑是,我将按开始日期对所有内容进行排序,然后为每一行分配排名。如果当前结束日期与上一个结束日期连续,也就是 datediff(end_date, @e) = 1,那么我将保持相同的排名数字,否则我会将排名递增 1。所以基本上所有的行都属于同一个项目会有相同的排名。

下面是我的代码:

set @r := 0;
select min(start_date), max(end_date)
from (select start_date, end_date,
@r := if(datediff(end_date, @e) = 1, @r, @r+1) ranking,
@e := end_date
from projects
order by start_date
) b
group by ranking
order by datediff(max(end_date), min(start_date)), 1
;

但是这段代码不起作用。

更新

根据 Sasha Pachev 的回答进行更改后,当我尝试检查子查询时:

set @r = 0;
select start_date, end_date,
@e := end_date, datediff(end_date, date(@e)),
@r := if(datediff(end_date, date(@e)), @r, @r+1) ranking
from projects
order by start_date
;

我注意到我所有的日期差异都是 0:

2015-10-01 2015-10-02 2015-10-02 0 1 
2015-10-02 2015-10-03 2015-10-03 0 2
2015-10-03 2015-10-04 2015-10-04 0 3
2015-10-04 2015-10-05 2015-10-05 0 4
2015-10-11 2015-10-12 2015-10-12 0 5
2015-10-12 2015-10-13 2015-10-13 0 6
2015-10-15 2015-10-16 2015-10-16 0 7
2015-10-17 2015-10-18 2015-10-18 0 8
2015-10-19 2015-10-20 2015-10-20 0 9

我明白为什么,因为我在分配排名@r 之前分配了@e 作为结束日期。但是,如果我在@r 之后分配@e,它就不起作用,因为我需要@e 为diffdate() 函数赋值。有人可以帮我打破这个循环吗?

最佳答案

SELECT         START_DATE, MIN(END_DATE) AS [END_DATE]
FROM (
(SELECT START_DATE
FROM PROJECTS
WHERE START_DATE NOT IN (SELECT END_DATE FROM PROJECTS)
) A
CROSS JOIN
(SELECT END_DATE
FROM PROJECTS
WHERE END_DATE NOT IN (SELECT START_DATE FROM PROJECTS)
) B
)
WHERE START_DATE < END_DATE
GROUP BY START_DATE
ORDER BY DATEDIFF(DAY, MIN(END_DATE), START_DATE) DESC, CAST(START_DATE AS DATE) ASC

关于MySQL:为什么日期差异总是0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41335541/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com