T-Sql

問題解決方案中的錯誤

  • February 27, 2019

我正在嘗試從hackerrank解決這個問題到目前為止我已經寫了這個解決方案

select Start_Date, min(End_Date)
from 
  (select Start_Date from projects where Start_Date not in (select End_Date from projects)),
  (select End_Date from projects where End_Date not in (select Start_Date from projects))
where Start_Date < End_Date 
group by Start_Date
order by datediff(day, min(End_Date), Start_Date) desc

但這表明這個答案是錯誤的,儘管當我比較時,我得到了我計劃得到的結果。我非常感謝能幫助我找出我錯在哪裡。 在此處輸入圖像描述

-- SET A MARK (RST=1) EVERY TIME PREVIOUS END_DATE IS NOT EQUAL START_DATE
WITH CT AS
(
   SELECT 
       TASK_ID, START_DATE, END_DATE,
       CASE WHEN (COALESCE(LAG(END_DATE) OVER (ORDER BY START_DATE), END_DATE) = START_DATE)
            THEN 0 ELSE 1 END RST
   FROM
       TASK
)
-- SUM(RST) TO SET A GROUP (1, 2, 3, ...)
, CT2 AS
(
   SELECT
       TASK_ID, START_DATE, END_DATE,
       SUM(RST) OVER (ORDER BY START_DATE) AS GRP
   FROM
       CT
)
SELECT 
   MIN(START_DATE) AS START_DATE,
   MAX(END_DATE) AS END_DATE
FROM 
   CT2
GROUP BY
   GRP;
START_DATE | 結束日期 
:------------------ | :------------------
01/10/2015 00:00:00 | 04/10/2015 00:00:00
13/10/2015 00:00:00 | 15/10/2015 00:00:00
28/10/2015 00:00:00 | 29/10/2015 00:00:00
30/10/2015 00:00:00 | 31/10/2015 00:00:00

db<>在這裡擺弄

引用自:https://dba.stackexchange.com/questions/230883