sql server - T-SQL IF statement embedded in a sum() function -
i'm attempting convert mysql query t-sql query , if statement that's enclosed within sum statement tripping me up. suggestions?
select cmts_rq.[dated], cmts_rq.cmts_name, count(cmts_rq.cmts_name) emat_count, sum(if(cmts_rq.us_pwr>=37 , cmts_rq.us_pwr<=49)) us_pwr_good cmts_rq group cmts_rq.cmts_name, cmts_rq.[dated]
but error:
msg 156, level 15, state 1, line 5
incorrect syntax near keyword 'if'.
msg 102, level 15, state 1, line 5
incorrect syntax near ')'.
t-sql doesn't have "inline" if
statement - use case
instead:
select cmts_rq.[dated], cmts_rq.cmts_name, count(cmts_rq.cmts_name) emat_count, sum(case when cmts_rq.us_pwr >=37 , cmts_rq.us_pwr <= 49 1 else 0 end) us_pwr_good cmts_rq group cmts_rq.cmts_name, cmts_rq.[dated]
so if value of cmts_rq.us_pwr
>= 37 , <= 49
add 1 sum
- otherwise 0. give you're looking for?
in sql server 2012 , newer, can use new iif
function:
sum(iif(cmts_rq.us_pwr >= 37 , cmts_rq.us_pwr <= 49, 1, 0)) us_pwr_good
Comments
Post a Comment