需要帮助JOIN和Condition

时间:2016-02-10 14:25:00

标签: sql if-statement join case

客户表:

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不为NULL,那么我想列出@archiveStartTimefromDateTime之间toDateTime所在的所有记录,projectDateOfCompletion为NULL。

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分: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 = '';`

查询难以阅读,所以也许我说错了。我的想法是:不是你在那里做的情况,而是像这样使用OR(如果查询没有运行,请调整你自己而不是案例)

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

答案 1 :(得分:0)

@Mureinik的查询       SELECT * FROM myTable       当id = 12345 AND((TermDate是NULL和            getdate()BETWEEN StartDate和DATEADD(dd,30,StartDate))或           GETDATE()< TermDate)

来自Add Case Statement in Where Clause

帮助解决了这个问题。谢谢@Mureinik