2015-08-31 55 views
0

即使條件爲真,該請求返回其他結果 「ELSE RESULT」。My sql如果條件爲真,則返回else結果

SELECT 
    IF(Print_Server_Type='BW',SUM(Total_Impressions_Printed),'ELSE RESULT') AS BWTotalImpressions 
FROM printedjob 
WHERE 
    Account='' 
    And Job_Submission_Date>="2015-08-24" 
    AND Job_Submission_Date<="2015-08-28"; 

與where條件相同的請求工作正常

SELECT 
    SUM(Total_Impressions_Printed) AS BWTotalImpressions 
FROM printedjob 
WHERE 
    Account='' 
    And Print_Server_Type='BW' 
    And Job_Submission_Date>="2015-08-24" 
    AND Job_Submission_Date<="2015-08-28"; 

我使用的第一個請求,因爲我需要的結果是從選擇一列。

+0

您可以編輯上面張貼含有這些行的表的樣本,與您所期望的查詢輸出爲樣品在一起嗎? –

回答

0

您正在混合總條件(如SUM(Total_Impressions_Printed))和單排條款(如Print_Server_Type)。好像你想每個值返回Print_Server_Type一排,這意味着你錯過了一個group by條款:

SELECT Print_Server_Type, 
     IF(Print_Server_Type = 'BW', 
      SUM(Total_Impressions_Printed), 
      'ELSE RESULT') AS BWTotalImpressions 
FROM  printedjob 
WHERE Account = '' AND 
     Job_Submission_Date >= "2015-08-24" AND 
     Job_Submission_Date <= "2015-08-28" 
GROUP BY Print_Server_Type 
+0

問題是數據包含BW和彩色Print_Server_Type –

0

我認爲你else語句不正確寫入。其他的不應該被引用'ELSE RESULT'...我會開始通過驗證以正確的格式來編寫查詢。

0

修正這個問題,這裏是要求:

Select Account,SUM(Total_Impressions),SUM(BWTotalImpressions) 
FROM (
    SELECT Account,Print_Server_Type,SUM(Total_Impressions_Printed) As Total_Impressions, 
    IF(Print_Server_Type='Color',SUM(Total_Color_Pages_Printed),'') AS ColorTotalImpressions, 
    IF(Print_Server_Type='BW',SUM(Total_Impressions_Printed), 
    IF(Print_Server_Type='Color',SUM(Total_Black_Only_Pages_Printed),'')) AS BWTotalImpressions 
    FROM printedjob 
    WHERE Job_Submission_Date>="2015-08-24" AND Job_Submission_Date<="2015-08-28" 
    GROUP BY Account,Print_Server_Type 
    )AS T 
GROUP by Account;