2013-05-13 57 views
8

我試圖將MySQL查詢轉換爲T-SQL查詢,並且包含在SUM語句中的IF語句正在讓我失望。有什麼建議麼?嵌入在sum()函數中的T-SQL IF語句

SELECT 
    CMTS_RQ.[Dated], 
    CMTS_RQ.CMTS_Name, 
    Count(CMTS_RQ.CMTS_Name) AS emat_count, 
    Sum(if(CMTS_RQ.US_Pwr>=37 and CMTS_RQ.US_Pwr<=49)) AS us_pwr_good 
FROM 
    CMTS_RQ 
GROUP BY 
    CMTS_RQ.CMTS_Name, 
    CMTS_RQ.[Dated] 

但我得到一個錯誤:

Msg 156, Level 15, State 1, Line 5
Incorrect syntax near the keyword 'if'.
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near ')'.

回答

16

T-SQL不具有 「內聯」 IF聲明 - 使用CASE代替:

SELECT 
    CMTS_RQ.[Dated], 
    CMTS_RQ.CMTS_Name, 
    Count(CMTS_RQ.CMTS_Name) AS emat_count, 
    Sum(CASE 
      WHEN CMTS_RQ.US_Pwr >=37 AND CMTS_RQ.US_Pwr <= 49 
      THEN 1 
      ELSE 0 
     END) AS us_pwr_good 
FROM 
    CMTS_RQ 
GROUP BY 
    CMTS_RQ.CMTS_Name, 
    CMTS_RQ.[Dated] 

因此,如果值CMTS_RQ.US_Pwr>= 37 AND <= 49然後加1到SUM - 否則爲0。這是否給你你正在尋找的?

在SQL Server 2012 更新,你可以使用新的IIF function

SUM(IIF(CMTS_RQ.US_Pwr >= 37 AND CMTS_RQ.US_Pwr <= 49, 1, 0)) AS us_pwr_good 
+1

+1使用的例子。 – Kermit 2013-05-13 18:44:28

+1

感謝您的洞察力,這指出我在正確的方向。 – user937036 2013-05-13 19:00:19