汽车表(汽车ID,Cus_id,Model,Delivery_Date,Reg_No)
101 1 Yaris - Active 05-Jan-2016 aa-168
102 1 Yaris 06-Jan-2017 ab-168
103 2 Fortuner 07-Jan-2017 aa-1111
104 3 Vios 08-Jan-2017 aa-1234
105 3 Altis 09-Feb-2017 ab-5555
106 4 Camry 10-Feb-2016 ab-9999
107 5 Hilux Revo 11-Feb-2017 aa-6666
服务表(Car_id,Service_Date,Service_Amount,Service_Detail)
101 05-Feb-2016 2565 1000km
101 10-Aug-2016 3400 10000km
101 20-Feb-2016 2100 20000km
102 06-Feb-2017 2565 1000km
103 07-May-2017 3400 10000km
104 08-Feb-2017 2565 1000km
105 09-May-2017 2565 1000km
106 10-Mar-2016 2565 1000km
106 15-Aug-2016 3400 10000km
106 20-Dec-2016 2100 20000km
我的目标是从两个表中查询值,以便其显示
预期表(型号,Reg_No,Last_Service,Previous_Service)
Yaris-Active aa-168 20-Feb-2016 10-Aug-2016
Yaris ab-168 06-Feb-2017 -
.............................................
Camry aa-9999 20-Dec-2016 15-Aug-2016
您会看到Last_Service将包含汽车使用该服务的最后日期,而Previous_Service将包含汽车在使用该服务之前的日期。我的基本步骤是在轿厢和服务台之间倾斜时,向左倾斜。
我打算执行的步骤是查询Car_id和Count(Car_id)并按Car_id分组,因为它将指示该汽车的存在数量。之后,使用计数值指示该模型的最后一行和最后第二行,并将值指定给指定的列...但是,我必须将其转换为SQL。...
SELECT Model, Reg_No, Service_Date As Last_Service, Service_Date As Previous_Date
FROM Car LEFT JOIN Service ON Car.Car_id = Service.Car_id
............................................... ......................
SELECT Car_id, Count(Car_id) As No.Times
From Service
Group BY Car_id
我需要帮助...
答案 0 :(得分:0)
在您第一次选择之前将其放置:
int main()
{
MyClass* array = function("some_file.txt");
// do something with the array above..
delete[] array; //clean up..
}
您现在可以将WITH countedservices AS(
SELECT *, ROW_NUMBER() OVER(PARTITION BY car_id ORDER BY service_date DESC) service_num
FROM service
)
连接到汽车桌两次-一次使用countedservices
,一次使用service_num = 1
来访问当前和以前的服务数据< / p>
如果您使用的是左联接,则不要在WHERE子句中强加这些谓词(大概是因为某些汽车将无法维修),因为它将左联接转换为内部联接。将它们放在ON子句中:
service_num = 2
答案 1 :(得分:0)
使用row_number()
根据service_dates
获取car_id
的序列,然后加入下一个序列。
select t1.Car_id, t1.Model, t1.Reg_No, t2.Service_Date as Last_Service, t1.Service_Date as Previous_Date
from
(select Car_id, Model, Reg_No, row_number() over (partition by Car_id order by s.Service_Date asc) rn, s.Service_Date
from Car c
inner join Service s on s.Car_id = s.Car_id) as t1
left join
(select Car_id, Model, Reg_No, row_number() over (partition by Car_id order by Service_Date asc) rn, s.Service_Date
from Car c
inner join Service s on s.Car_id = s.Car_id) as t2 on t2.Car_id = t1.Car_id and t2.rn + 1 = t1.rn
答案 2 :(得分:0)
像这样尝试...
SELECT Model,
Reg_No,
Service_Date
INTO #Temp_Output_1
FROM Temp_Car Car
JOIN Temp_Service Servic
ON (Car.Car_id = Servic.Car_id)
SELECT Model,
Reg_No,
Service_Date,
(SELECT MAX(Service_Date) FROM #Temp_Output_1 T1 WHERE T1.Reg_No = T2.Reg_No AND T1.Service_Date < T2.Service_Date) AS Prev_Service_Date
FROM #Temp_Output_1 T2
WHERE T2.Service_Date = (
SELECT MAX(Service_Date)
FROM #Temp_Output_1 T3
WHERE T2.Reg_No = T3.Reg_No
)