簡體   English   中英

sql server 2005和.net查詢

[英]sql server 2005 and .net query

首先,我將解釋表格的概念。
我有3張桌子, A,BC

表A包含新舊許可證號,以及驅動程序更改新許可證的日期

表A包含

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

表B記錄了許可證號和汽車ID ,以及他們使用汽車的第一天 請注意,在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

更新: @Szymon thnx也提供了幫助,也為kumarch1提供了幫助
在圖像上,許可證號222333 = 2(在問題上)和13213113 = 3 新增表格

經過澄清,這將是您的查詢。 它根據日期查找許可證的更改。

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演示

將您的數據保存在臨時模板中,並從臨時表中檢索數據,而不要使用null

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM