你好我这里有一个车辆检查数据库,我在sql中有一个代码,它给我第二个和后续的EventTime或大于Min(EventTime)和相应的TicketStatus。表是[Event]和[Car] ... [Event]表有字段CarID(FK); EVENTTIME; TicketStatus ...在[Car]表上有字段CarID(PK); PlateNo;套餐
注意:[Car] .CarID数据类型是唯一标识符Ex。 {16F0151E-1938-4487-BB75-FF446B4DB7FF}
执行代码将为我提供CarID,EventTime,TicketStatus。我不想要CarID作为结果,我想从表[Car],TicketStatus,EventTime和标准[Car] .Package = 4
中获得PlateNoSELECT CarID, TicketStatus, [EventTime]
FROM
(SELECT ROW_NUMBER() OVER
(PARTITION BY CarID ORDER BY [EventTime] ASC) AS [index]
, CarID, TicketStatus, [EventTime]
FROM vehicle.dbo.Event Event) A
WHERE [index] > 1
答案 0 :(得分:1)
如果我理解你想要的是什么,你需要JOIN
和Car
这样的表
SELECT c.PlateNo, TicketStatus, EventTime
FROM
(
SELECT ROW_NUMBER() OVER
(PARTITION BY CarID ORDER BY EventTime) AS rnum
, CarID, TicketStatus, EventTime
FROM Event
) a JOIN Car c
ON a.CarID = c.CarID
WHERE c.Package = 4
AND a.rnum > 1
或
SELECT PlateNo, TicketStatus, EventTime
FROM
(
SELECT e.CarID, e.TicketStatus, e.EventTime, c.PlateNo,
ROW_NUMBER() OVER
(PARTITION BY e.CarID ORDER BY e.EventTime) AS rnum
FROM Event e JOIN Car c
ON e.CarID = c.CarID
WHERE c.Package = 4
) a
WHERE a.rnum > 1
这是 SQLFiddle 演示