2015-01-21 42 views
1

我有一组关于面包车(序列号,工作号,工作类型和当前里程)的记录。SQL显示记录发生在字段中某个特定日期类型的最新信息后

select serial_number, call_ref, call_type_description, callm_data19 
from calls 
left join equipment on link_to_equipment=equipment_code 
inner join lu_call_types on call_type=call_type_code 
left join call_more on call_ref=callm_link_to_call 
where serial_number = 'SH12ZLN' 
order by call_ref desc 

我希望能够显示在最近的“面包车服务”记录后发生的下一个“面包车检查”记录。

这里是数据

SH12ZLN 3023152 Van Inspection 83980 
SH12ZLN 3019319 Van Inspection 83046 
SH12ZLN 3016999 Van Servicing NULL 
SH12ZLN 3016346 Van Inspection 81818 
SH12ZLN 3012977 Van Inspection 80742 
SH12ZLN 3010435 Van Inspection 79909 
SH12ZLN 3008528 Van Repairs NULL 
SH12ZLN 3006880 Van Inspection 78577 
SH12ZLN 3001942 Van Inspection 76974 
SH12ZLN 2998209 Van Inspection 75976 
SH12ZLN 2994475 Van Inspection 75285 
SH12ZLN 2991756 Van Repairs NULL 
SH12ZLN 2989642 Van Inspection 74408 
SH12ZLN 2985795 Van Inspection 73642 
SH12ZLN 2981952 Van Inspection 72838 
SH12ZLN 2978257 Van Inspection 72011 
SH12ZLN 2975667 Van Inspection 70692 
SH12ZLN 2972244 Van Inspection 69732 
SH12ZLN 2969157 Van Inspection 68821 
SH12ZLN 2959335 Van Inspection 67891 
SH12ZLN 2956295 Van Inspection 66994 
SH12ZLN 2948516 Van Inspection 66481 
SH12ZLN 2946213 Van Inspection 65778 
SH12ZLN 2939497 Van Inspection 64408 
SH12ZLN 2937538 Van Inspection 63765 
SH12ZLN 2934421 Van Inspection 62937 
SH12ZLN 2932707 Van Inspection 61645 
SH12ZLN 2930711 Van Inspection 60713 
SH12ZLN 2930023 Van Inspection 59683 
SH12ZLN 2924989 Van Inspection 58372 
SH12ZLN 2924830 Van Repairs NULL 
SH12ZLN 2922412 Van Inspection 57474 
SH12ZLN 2919005 Van Servicing NULL 
SH12ZLN 2918376 Van Repairs NULL 

澄清的快照 - 我希望它只能产生以下记录

SH12ZLN 3019319 Van Inspection 83046 
+0

请在13个帖子后学会格式化您的问题 – 2015-01-21 10:11:05

+0

我刚刚在编辑过程中纠正格式,当你这样做。 – chenks 2015-01-21 10:11:49

+0

请在将来发布之前进行。您可以在编辑器下方的预览中看到它的外观。 – 2015-01-21 10:17:51

回答

0

问题澄清我已经编辑我的答案后。 为了解决这个问题,你应该找到最新的'Van服务'类型的job_number,这意味着最近的一个。你将其与子查询可能:

SELECT MAX(job_number) FROM tbl WHERE id = 'SH12ZLN' AND type = 'Van Servicing' 

你之后,你有最近的维修job_number只是job_number高于最近发现并选择行与最低job_number过滤行。

最终的查询可能看起来像以下:

SELECT TOP 1 * FROM tbl WHERE 
job_number > (SELECT MAX(job_number) FROM tbl WHERE id = 'SH12ZLN' 
    AND type = 'Van Servicing') 
AND type = 'Van Inspection' 
ORDER BY job_number ASC 

退房sqlfiddle尝试一下:http://sqlfiddle.com/#!3/64dfc/2

附:正如我可以从最初的问题,你的样本数据是从查询本身收到的。您的查询可能会增强以返回所需,但我需要所有表的模式。

+0

这只会返回一条记录。 – 2015-01-21 10:15:45

+0

这似乎按预期工作(虽然我不得不做一个小的改变) – chenks 2015-01-21 14:20:17

+0

好奇知道这种改变。 – 2015-01-21 14:25:45

相关问题