SQL 2 counts with different filter

后端 未结 6 1293
故里飘歌
故里飘歌 2020-12-21 02:56

I have a table and I need calculate two aggregate functions with different conditions in one statement. How can I do this?

Pseudocode below:

SELECT c         


        
6条回答
  •  清歌不尽
    2020-12-21 03:19

    SELECT
    SUM(IF(CoumntA < 0, 1, 0)) AS lowerThanZero,
    SUM(IF(CoumntA > 0, 1, 0)) AS greaterThanZero
    FROM
    TableA
    

    Is it clear what's happening? Ask, if you have any more questions.

    A shorter form would be

    SELECT
    SUM(CoumntA < 0) AS lowerThanZero,
    SUM(CoumntA > 0) AS greaterThanZero
    FROM
    TableA
    

    This is possible, since in MySQL a true condition is equal 1, a false condition is equal 0

    EDIT: okay, okay, sorry, don't know why I thought it's about MySQL here.

    See the other answers about correct syntax.

提交回复
热议问题