2013-10-29 131 views
0

我希望下面的查詢根據日期範圍命名大小寫欄 - 但是,所有都默認爲錯誤 - 我錯過了什麼?自從我在mySQL工作以來已經有相當長的一段時間了。我試圖根據逾期,今天,明天,30天,60天,90天的時間間隔進行分組。在Select語句中使用CASE

SELECT DATE_SUB(CURDATE(), INTERVAL 1 DAY)AS rDate, 

    CURDATE()AS rDate,DATE_ADD(CURDATE(), INTERVAL 1 DAY)AS rDate, 

    DATE_ADD(CURDATE(), INTERVAL 7 DAY)AS rDate, 

    DATE_ADD(CURDATE(), INTERVAL 14 DAY)AS rDate, 

    DATE_ADD(CURDATE(), INTERVAL 30 DAY)AS rDate, 

    DATE_ADD(CURDATE(), INTERVAL 60 DAY)AS rDate, 

    DATE_ADD(CURDATE(), INTERVAL 90 DAY)AS rDate, 

    CASE a.nextDueDate 

    WHEN a.nextDueDate < CURDATE() THEN 'Overdue' 

    WHEN a.nextDueDate > CURDATE() AND a.nextDueDate < (DATE_ADD(CURDATE(), INTERVAL 7 
    DAY))THEN '7 Days' 

    WHEN a.nextDueDate > CURDATE() AND a.nextDueDate < (DATE_ADD(CURDATE(), INTERVAL 
    14 DAY))THEN '15 Days' 

    WHEN a.nextDueDate > CURDATE() AND a.nextDueDate < (DATE_ADD(CURDATE(), INTERVAL 30 DAY))THEN '30 Days' 

    WHEN a.nextDueDate > CURDATE() AND a.nextDueDate < (DATE_ADD(CURDATE(), INTERVAL 60 DAY))THEN '60 Days' 

    WHEN a.nextDueDate > CURDATE() AND a.nextDueDate < (DATE_ADD(CURDATE(), INTERVAL 90 DAY))THEN '90 Days' 

    ELSE 'Error' 

    END, 

    g.groupId,g.name AS groupName,l.logId,l.name AS logName, i.itemID, 

    i.name AS itemName, le.userName,completed, i.optimalMin,i.optimalMax ,le.value, 

    u.name AS unitDescription, 

    g1.parentId AS parentId1, g1.name AS group1Name,g2.parentId AS parentId2, g2.name 
    AS group2Name, 

    g3.parentId AS parentId3, g3.name AS group3Name, 

    a.name AS activityName,scheduleType,scheduleInterval,a.details,nextDueDate 

    FROM logExceptions le 

    INNER JOIN logs l ON l.logID = le.logID 

    INNER JOIN groups g ON g.groupId = l.groupId 

    INNER JOIN items i ON le.itemId = i.itemId 

    INNER JOIN activities a ON l.logId = a.logId 

    LEFT JOIN units u ON i.unitId = u.unitId 

    LEFT JOIN groups g1 ON g.parentId = g1.groupId 

    LEFT JOIN groups g2 ON g1.parentId = g2.groupId 

    LEFT JOIN groups g3 ON g2.parentId = g3.groupId 

    WHERE nextDueDate IS NOT NULL 

回答

2

CASE關鍵字後刪除a.nextDueDate

CASE表達有兩種形式:

CASE <expression> 
    WHEN <test-value1> THEN <result-value1> 
    WHEN <test-value2> THEN <result-value2> 
    ... 
    ELSE <else-value> 
END 

在這種形式中,<expression>值針對每個<test-valueN>比較,並且它匹配時,則返回相應的<result-valueN>。如果沒有匹配,則返回<else-value>。這種形式類似於其他編程語言中的switchcase語句。

另一種形式是:

CASE WHEN <test-expression1> THEN <result-value1> 
    WHEN <test-expression2> THEN <result-value2> 
    ... 
    ELSE <else-value> 
END 

在這種情況下,每個被<test-expressionN>評估,並且如果當有一個爲真則返回相應的<result-valueN>。如果沒有,則返回<else-value>。這與其他編程語言中的if/then/elseif/else類似。

由於您使用的是後一種類型的CASE,因此您不應在CASE之後有表達式。

+0

完美解釋 - 非常感謝! – Portlight