SQL 2 counts with different filter

后端 未结 6 1262
故里飘歌
故里飘歌 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:25

    It is possible to do this in one select statement.

    The way I've done it before is like this:

    SELECT SUM(CASE WHEN ColumnA < 0 THEN 1 END) AS LessThanZero, 
           SUM(CASE WHEN ColumnA > 0 THEN 1 END) AS GreaterThanZero
    FROM dbo.TableA 
    

    This is the correct MS SQL syntax and I believe this is a very efficient way of doing it.

    Don't forget you are not covering the case when ColumnA = 0!

提交回复
热议问题