2013-12-17 277 views
0

首先,我将解释表的概念..
我有3个表,A,BçSQL Server 2005和.NET查询

表A中包含新与旧牌照号码,也是日期当司机换了新的许可证

表A中包含

fdate      | oldLicense (varchar) | newLicense (varchar) 
12/14/2013 4:16:16 PM  | 2      | 3 

表B记录了许可证号和车号,还有第一天当他们用车时。请注意,在2013年12月14日,插入了新的许可证号码,这意味着司机在车上更换,因为旧车不能再行驶或已经死亡)。

表B含有

ID_Car | licenseNumber | fDate 
44  | 2    | 12/9/2013 4:16:16 AM 
44  | 3    | 12/14/2013 4:16:16 PM 

表C是对汽车进行的维修。注意它有日期,它应该反映何时驱动程序被改变
例如,在2013年12月9日的驾照仍然为2,并在2013年12月15日的许可证已经是3

表C包含

Invoice | ID_Car | fDate 
00989  | 44  | 12/9/2013 5:00:00 AM 
10100  | 44  | 12/9/2013 6:00:00 AM 
32323  | 44  | 12/15/2013 12:00:00 AM 

所需的输出:

C.Invoice | A.Licenses (old and new?) 
00989  | 2 
10100  | 2 
32323  | 3 

我迄今为止尝试是:

SELECT B.fInvoice, C.fLicenseNew 
FROM tblCarFranchise A 
LEFT JOIN tblCarMaintenance B ON A.ID_Car = B.ID_Car 
LEFT JOIN tblTaxiDriversRelation C ON A.fLicenseNumber = C.fLicenseNew 

输出:

00989  | NULL 
10100  | NULL 
32323  | NULL 
00989  | 3 
10100  | 3 
32323  | 3 

我真的不知道我应该如何开始这一点,这可能是我面临迄今为止最复杂的查询,也排在某种程度上复制(共6行,而不是3行)

帮助T_T

UPDATE: @Szymon日Thnx帮助,也kumarch1
上的图像,车牌号码222333 = 2(对这个问题)和13213113 = 3 Added tables

+0

检查答案下面定义从 –

+0

变化<>来!= –

回答

1

澄清后,这将是你的查询。它根据日期查找许可证的更改。

select C.fInvoice, B.fLicenseNumber 
from tblCarMaintenance C 
inner join tblCarFranchise B 
on C.ID_Car = B.ID_Car 
and C.fDate >= B.fdate 
and C.fDate < isnull((select top 1 fDate from tblCarFranchise M where M.fdate > B.fdate 
       and M.ID_Car = B.ID_Car), '20991231') 

SQL Fiddle demo

+0

你能告诉我是什么“20991231”是指在查询? – Codemunkeee

+0

在遥远的将来的日期。我匹配的发票之间的许可证的变化,这就是我如何找到最后的许可证(这是在最后的变化和2099年之间。 – Szymon

+1

哦,好吧谢谢:)它的工作在小提琴,但我仍然调整代码在SQL服务器和我的代码上工作。我会马上回答这个答案,只要我得到它:) – Codemunkeee

0

保持在一个临时的寺庙数据并没有空置检索临时表中的数据

Select temp.fInvoice ,temp.fLicenseNew from(SELECT B.fInvoice as fInvoice , C.fLicenseNew as fLicenseNew 
FROM tblCarFranchise A 
LEFT JOIN tblCarMaintenance B ON A.ID_Car = B.ID_Car 
LEFT JOIN tblTaxiDriversRelation C ON A.fLicenseNumber = C.fLicenseNew) temp 
where temp.fLicenseNew != null 
+0

谢谢兄弟,但没有返回任何行..嗯 – Codemunkeee