I'm attempting to convert a MySQL query to a T-SQL query and the IF statement that's enclosed within a SUM statement is tripping me up. Any suggestions?
我正在尝试将MySQL查询转换为T-SQL查询,并且包含在SUM语句中的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]
But I get an error:
但是我收到一个错误:
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 ')'.消息156,级别15,状态1,行5关键字“if”附近的语法不正确。消息102,级别15,状态1,行5'''附近的语法不正确。
1 个解决方案
#1
16
T-SQL doesn't have a "inline" IF
statement - use a CASE
instead:
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]
So if the value of CMTS_RQ.US_Pwr
is >= 37 AND <= 49
then add 1 to the SUM
- otherwise 0. Does that give you what you're looking for?
因此,如果CMTS_RQ.US_Pwr的值> = 37 AND <= 49,则向SUM添加1 - 否则为0.这是否可以为您提供所需内容?
In SQL Server 2012 and newer, you can use the new IIF
function:
在SQL Server 2012及更高版本中,您可以使用新的IIF功能:
SUM(IIF(CMTS_RQ.US_Pwr >= 37 AND CMTS_RQ.US_Pwr <= 49, 1, 0)) AS us_pwr_good
#1
16
T-SQL doesn't have a "inline" IF
statement - use a CASE
instead:
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]
So if the value of CMTS_RQ.US_Pwr
is >= 37 AND <= 49
then add 1 to the SUM
- otherwise 0. Does that give you what you're looking for?
因此,如果CMTS_RQ.US_Pwr的值> = 37 AND <= 49,则向SUM添加1 - 否则为0.这是否可以为您提供所需内容?
In SQL Server 2012 and newer, you can use the new IIF
function:
在SQL Server 2012及更高版本中,您可以使用新的IIF功能:
SUM(IIF(CMTS_RQ.US_Pwr >= 37 AND CMTS_RQ.US_Pwr <= 49, 1, 0)) AS us_pwr_good