2016-02-10 51 views
0

Customer表:需要幫助的JOIN和條件

customerId customerName startTime projectDateOfCompletion 
1   ANZ    2015-12-05  NULL 
2   Barklays  2015-11-25  2016-02-10 
3   Grindlays  2016-02-06  NULL 

報告表:

customerId repId fromDateTime toDateTim 
1   1  2015-12-05  2016-02-05 
1   2  2016-02-06   NULL 
2   3  2015-11-25  2016-02-10 
3   1  2016-02-08   NULL 

CustomerSupport表:

repId customerSupportRep 
1  Jim Daniel  
2  Mark Chad  
3  Juan Maximo 

不確定如何以表格形式格式化表格。希望看起來像表格。我在尋找幫助,下面的查詢

SELECT 
    t.customerName AS 'Customer Name', 
    u.customerSupportRep AS 'Customer Support Representative', 
    t.startTime AS 'Start Date/Time' 
FROM Customer t 
    JOIN CustomerSupport u 
     ON u.repId = (SELECT repId 
         FROM Reports 
         WHERE 
          customerId = t.customerId AND 
          (CASE 
           WHEN (@archiveStartTime IS NOT NULL) 
            then @archiveStartTime BETWEEN fromDateTime AND toDateTime 
           ELSE toDateTime IS NULL 
          END) 
        )       
    WHERE 
     t.projectDateOfCompletion IS NULL OR 
     t.projectDateOfCompletion = ''; 

如果@archiveStartTime爲NULL,我想與projectDateOfCompletion記錄爲NULL 如果@archiveStartTime不爲空,然後我想列出所有記錄中,其中@archiveStartTime在於fromDateTime之間toDateTimeprojectDateOfCompletion爲NULL。

任何幫助將不勝感激。

回答

0

試試這個:

`SELECT t.customerName AS 'Customer Name', u.customerSupportRep AS 'Customer Support Representative', t.startTime AS 'Start Date/Time' 
FROM Customer t 
    JOIN CustomerSupport u ON u.repId = (SELECT repId FROM Reports WHERE customerId = t.customerId AND 
     ((@archiveStartTime IS NOT NULL 
      and @archiveStartTime BETWEEN fromDateTime AND toDateTime) 
     or (@archiveStartTime IS NULL AND toDateTime IS NULL) 
     )) 
    WHERE t.projectDateOfCompletion IS NULL OR t.projectDateOfCompletion = '';` 

查詢難以閱讀,所以也許我已經把情況不對。我的想法是:相反的情況下,你也有,使用或像這樣(如果查詢不運行進行調整你的自我,而不是這種情況)由@Mureinik
SELECT * FROM

AND 
     ((@archiveStartTime IS NOT NULL 
      and @archiveStartTime BETWEEN fromDateTime AND toDateTime) 
     or (@archiveStartTime IS NULL AND toDateTime IS NULL)) 
+0

謝謝@sagi,這工作。 –

0

這個查詢myTable的 在ID = 12345 AND((TermDate IS NULL和 GETDATE()之間的起始日期和DATEADD(DD,30,起始日期))或 GETDATE()< TermDate)

Add Case Statement in Where Clause 幫助解決這個問題。謝謝@Mureinik