MSSQL使用IF()语句选择查询

时间:2015-02-03 13:47:38

标签: sql-server mssql-jdbc

我有MYSQL查询,它的工作正常 QUERY是:

SELECT * , IF(totexec >= totexecrun1, totexec-totexecrun1,0)  AS rewrk, 
      SUM(tcu) tcunit , 
      IF(totexec=0, ((SUM(tcu)/totexec)*100),0) AS proflevel 
FROM mntest_schedule a 
LEFT JOIN mnrelease_details b 
   ON b.tester=a.tester 
   AND a.project=b.project 
LEFT JOIN tc_details c 
   ON b.tc_id=c.tc_name 
   AND a.project=c.project 
WHERE a.rel_name='automanual_assign' 
AND a.project='JupiterQA' 
GROUP BY a.tester;

我试图在MSSQL中执行相同的查询但是它的抛出错误。 错误是:

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

我对这个查询做错了吗?

2 个答案:

答案 0 :(得分:1)

SELECT  * ,
        CASE WHEN totexec >= totexecrun1 THEN totexec - totexecrun1
             ELSE 0
        END AS rewrk ,
        SUM(tcu) tcunit ,
        CASE WHEN totexec = 0 THEN ( SUM(tcu) / totexec ) * 100
             ELSE 0
        END AS proflevel
FROM    mntest_schedule a
        LEFT JOIN mnrelease_details b ON b.tester = a.tester
                                         AND a.project = b.project
        LEFT JOIN tc_details c ON b.tc_id = c.tc_name
                                  AND a.project = c.project
WHERE   a.rel_name = 'automanual_assign'
        AND a.project = 'JupiterQA'
GROUP BY a.tester;

答案 1 :(得分:0)

使用CASE代替IF。 请参阅this(了解SQL Server中的案例表达示例)以了解CASE中的SQL SERVER.

 SELECT * , 
    CASE WHEN (totexec >= totexecrun1) 
         THEN totexec-totexecrun1 
         ELSE 0 END  AS rewrk, 
    SUM(tcu) tcunit , 
    CASE WHEN (totexec=0) 
        THEN ((SUM(tcu)/totexec)*100) 
        ELSE 0 END AS proflevel 
FROM mntest_schedule a LEFT JOIN mnrelease_details b 
ON b.tester=a.tester AND a.project=b.project 
LEFT JOIN tc_details c ON b.tc_id=c.tc_name AND a.project=c.project 
WHERE a.rel_name='automanual_assign' AND a.project='JupiterQA' 
GROUP BY a.tester;