在同一SQL请求中执行两个计数(具有不同条件)

时间:2015-09-28 16:56:55

标签: sql select count case sybase

我必须在Sybase引擎上运行以下两个查询:

SELECT COUNT(*) AS BTB_YES FROM FXMM_EVT_DBF WHERE M__INTID_ = '1.511' AND M_ISHEDGE = 1
SELECT COUNT(*) AS BTB_NO FROM FXMM_EVT_DBF WHERE M__INTID_ = '1.511' AND M_ISHEDGE = 0

因为我基本上选择了同一组信息,即:

SELECT M_ISHEDGE
FROM FXMM_EVT_DBF
WHERE M__INTID_ = '1.511'

然后我依靠两个单独的条件依次对这个列进行了两次,我觉得有一种方法可以在同一个查询上得到结果,这很好,因为上面的查询必须在几个数据库上运行。

但是,我无法获得联合结果,可能是因为我不擅长SQL。我的尝试是:

SELECT M_ISHEDGE
FROM FXMM_EVT_DBF WHERE M__INTID_ = '1.511'
CASE WHEN M_ISHEDGE = 1
    then count(*)
    else 0
END AS BTB_YES
CASE WHEN M_ISHEDGE = 0
    then count(*)
    else 0
END AS BTB_NO

但上述操作失败并出现以下错误:

An error occurred when executing the SQL command:
SELECT M_ISHEDGE
FROM FXMM_EVT_DBF WHERE M__INTID_ = '1.511'
CASE WHEN M_ISHEDGE = 1
    then count(*)
    else 0
END AS BTB_Y...
Incorrect syntax near the keyword 'CASE'. [SQL State=ZZZZZ, DB Errorcode=156] 

Execution time: 0s

1 statement(s) failed.

并且SQL编辑器似乎没有识别关键字THEN,尽管它是文档的一部分,因此可能是因为某些语法错误。

2 个答案:

答案 0 :(得分:1)

你对case表达式有正确的想法,但正如你所注意到的那样,语法错误。这里的想法是count省略了null s,因此您希望将count函数本身应用于case表达式:

SELECT COUNT (CASE M_ISHEDGE WHEN 1 THEN 1 ELSE NULL END) AS BTB_YES,
       COUNT (CASE M_ISHEDGE WHEN 0 THEN 1 ELSE NULL END) AS BTB_NO
FROM   FXMM_EVT_DBF 
WHERE  M__INTID_ = '1.511'

答案 1 :(得分:1)

您想要在count函数中移动case表达式,如下所示:

SELECT 
    COUNT(CASE WHEN M_ISHEDGE = 1 then m_ishedge end) AS BTB_YES,
    COUNT(CASE WHEN M_ISHEDGE = 0 then m_ishedge end) AS BTB_NO
FROM 
    FXMM_EVT_DBF 
WHERE 
    M__INTID_ = '1.511'

由于case表达式返回null,如果没有when条件匹配,则可以省略else部分(count仅计算非空值)