如何纠正这个SQL语句?

问题描述 投票:0回答:1

服务台:

汽车_id 服务日期
101 2016-02-05
102 2017-02-06
103 2017-05-07
104 2017-02-08
105 2017-05-09
106 2016-03-10
101 2016-08-10
101 2016-02-20
106 2016-08-15
106 2016-12-20

预期结果:

汽车_id 服务_日期(最后) 服务_日期(上一个)
101 2016-08-10 2016-02-20
102 2017-02-06 -
103 2017-05-07 -
104 2017-02-08 -
105 2017-05-09 -
106 2016-12-20 2016-08-15
107 - -
108 - -

我当前的代码:

WITH B AS
(
    SELECT 
        A.Car_id, A.Service_Date AS Last, 
        LAG(A.Service_Date) OVER (ORDER BY A.Service_Date) AS Previous
    FROM 
        Service AS A
)
SELECT 
    E.Car_id, F.Last, F.Previous
FROM 
    ((SELECT C.Car_id, C.Last, C.Previous
      FROM 
          (SELECT
               B.Car_id, B.Last, B.Previous, 
               ROW_NUMBER() OVER (PARTITION BY B.Car_id ORDER BY B.Last DESC) AS k
           FROM 
               B) AS C
      WHERE C.K = 1)) AS F 
RIGHT JOIN 
    Car AS E ON F.Car_id = E.Car_id  

我目前的输出:

汽车_id 服务_日期(最后) 服务_日期(上一个)
101 2016-08-10 2016-03-10
102 2017-02-06 2016-12-20
103 2017-05-07 2017-02-08
104 2017-02-08 2017-02-06
105 2017-05-09 2017-05-07
106 2016-12-20 2016-08-15
107
108

右连接用于从我临时删除的其他表中提取一些列。该代码的问题在于前一个日期列中的某些值似乎不正确。如果没有其他服务日期,则之前的日期列应包含“-”

Car_ID
Car_ID = 107
108
尚未收到任何服务,因此它们位于服务表中。我认为需要使用
CASE
语句,但我似乎不知道将其放置在哪里。

sql sql-server subquery common-table-expression
1个回答
0
投票

需要车旁隔断。一旦我们这样做了,我们就可以将其降低到一层嵌套:

WITH windowed As 
(
    SELECT Car_ID, Service_Date
        , LAG(Service_Date) OVER (PARTITION BY Car_ID ORDER BY Service_Date) Prev
        , ROW_NUMBER() OVER (PARTITION BY Car_ID ORDER BY Service_Date DESC) rn
    FROM Service
)
SELECT c.Car_ID, Service_Date As [Service_Date(Last)], Prev As [Service_Date(Previous)]
FROM Car c
LEFT JOIN Windowed w ON w.Car_ID = c.Car_ID AND w.rn = 1
ORDER BY c.Car_ID

在这里查看它的工作原理(感谢巴特开始小提琴):

https://dbfiddle.uk/ymWlnkjy

© www.soinside.com 2019 - 2024. All rights reserved.