2013-07-24 127 views
0

我想爲我現在手動完成的某些事情想出一個自動化解決方案,而且我只有最小的,基本的SQL技能。我通常修改其他人構建的簡單查詢或將構建基本的選擇查詢。我已經做了一些閱讀,但不知道如何在這種情況下做到我所需要的。我需要拿出別人在外出一個月時可以使用的東西(當我返回時,這會節省我的時間)。SQL查詢:比較返回記錄中的兩個日期

我需要的是返回下面的字段,其中tblThree.EndDate晚於tblFive.ServiceEnd。我必須在日期上做一些其他比較,但如果我得到第一個工作查詢,我可以使其與其他人一起工作。我們使用MS SQL Server 2008.

我試圖用別名創建子查詢,並失敗悲慘地使它工作。

這些表和字段我一起工作:

tblOne.ServiceID 
    tblOne.ServiceYear 
    tblOne.Status 
    tblTwo.AccountNbr 
    tblTwo.AcctName 
    tblThree.BeginDate (smalldatetime, null) 
    tblThree.EndDate (smalldatetime, null) 
    tblFour.ClientID 
    tblFour.ServiceName 
    tblFive.ContractID 
    tblFive.ServiceBegin (smalldatetime, null) 
    tblFive.ServiceEnd (smalldatetime, null) 

這是怎樣的表相關:

tblOne.ServiceID = tblThree.ServiceID 
    tblOne.ContractID = tblFive.ContractID 
    tblOne.ClientID = tblFour.ClientID 
    tblTwo.AccountNbr = tblFour.Account 

我使用的MS Access 2003來生成連接SQL:

SELECT tblOne.ServiceID, tblTwo.AccountNbr, 
    tblTwo.AcctName, tblFour.ServiceName, tblOne.Status, 
    tblThree.BeginDate, tblThree.EndDate, 
    tblOne.ServiceYear, tblFive.ServiceBegin, 
    tblFive.ServiceEnd 

FROM ((tblTwo INNER JOIN tblFour 
    ON tblTwo.AccountNbr=tblFour.AccountNbr) INNER JOIN (tblThree INNER JOIN tblOne 
    ON tblThree.ServiceID=tblOne.ServiceID) 
    ON tblFour.ClientID=tblOne.ClientID) INNER JOIN tblFive 
    ON tblOne.ContractID=tblFive.ContractID; 

感謝您的任何幫助。

回答

0

只需添加一個WHERE子句開始:

SELECT tblOne.ServiceID, tblTwo.AccountNbr, 
    tblTwo.AcctName, tblFour.ServiceName, tblOne.Status, 
    tblThree.BeginDate, tblThree.EndDate, 
    tblOne.ServiceYear, tblFive.ServiceBegin, 
    tblFive.ServiceEnd 

FROM ((tblTwo INNER JOIN tblFour 
    ON tblTwo.AccountNbr=tblFour.AccountNbr) INNER JOIN (tblThree INNER JOIN tblOne 
    ON tblThree.ServiceID=tblOne.ServiceID) 
    ON tblFour.ClientID=tblOne.ClientID) INNER JOIN tblFive 
    ON tblOne.ContractID=tblFive.ContractID 
WHERE tblThree.EndDate > tblFive.ServiceEnd; 
0
SELECT 
    tblOne.ServiceID, 
    tblOne.ServiceYear, 
    tblOne.Status, 
    tblTwo.AccountNbr, 
    tblTwo.AcctName, 
    tblThree.BeginDate, 
    tblThree.EndDate, 
    tblFour.ClientID, 
    tblFour.ServiceName, 
    tblFive.ContractID, 
    tblFive.ServiceBegin, 
    tblFive.ServiceEnd 
FROM tblOne 
INNER JOIN tblThree 
ON tblOne.ServiceID = tblThree.ServiceID 
INNER JOIN tblFive 
ON tblOne.ContractID = tblFive.ContractID 
INNER JOIN tblFour 
ON tblOne.ClientID = tblFour.ClientID 
INNER JOIN tblTwo 
ON tblTwo.AccountNbr = tblFour.Account 
WHERE tblThree.EndDate > tblFive.ServiceEnd