SQL帮助:我有一份服务时间为六年的汽车列表,我需要获取7月13日之前服务的汽车数据,此后不再提供服务
SELECT j.customer_id, m.name,j.car_id, c.model, c.reg_num, c.chassis_num, c.vin_num, c.engine_num, j.id AS jobcard_id, j.raw_jobcard_id, j.workshop_id, l.name AS workshop_name, j.jobcard_num, j.bill_date AS jobcard_date
FROM jobcards j
LEFT JOIN cars c ON j.car_id = c.id
LEFT JOIN customers m ON j.customer_id = m.id
LEFT JOIN locations l ON j.workshop_id = l.id
WHERE j.bill_date < '2013-07-01'
GROUP BY j.car_id
答案 0 :(得分:1)
您可以使用以下方式获取汽车列表:
select j.car_id
from jobcards j
group by j.car_id
having max(j.bill_date) < '2013-07-01';
如果您想要问题中的所有细节,那么每辆车需要多行。您可以使用join
,exists
或in
来实现此目的:
SELECT j.customer_id, m.name, j.car_id, c.model, c.reg_num, c.chassis_num,
c.vin_num, c.engine_num, j.id AS jobcard_id, j.raw_jobcard_id,
j.workshop_id, l.name AS workshop_name, j.jobcard_num,
j.bill_date AS jobcard_date
FROM jobcards j JOIN
cars c
ON j.car_id = c.id JOIN
customers m
ON j.customer_id = m.id JOIN
locations l
ON j.workshop_id = l.id
WHERE c.id IN (select j.car_id
from jobcards j
group by j.car_id
having max(j.bill_date) < '2013-07-01'
)
ORDER BY c.id;
我不明白为什么LEFT JOIN
在这种情况下是必要的。
答案 1 :(得分:0)
SELECT DISTINCT carName, ....
FROM table
WHERE serviceDate < '2016-07-13' and serviceDate >= DATEADD(year,-6,GETDATE())