SQL 2 score with different filter
As @tombom showed, this one can run as a single request. But that doesn't mean it should be.
SELECT
SUM(CASE WHEN CoumntA < 0 THEN 1 ELSE 0 END) AS less_than_zero,
SUM(CASE WHEN CoumntA > 0 THEN 1 ELSE 0 END) AS greater_than_zero
FROM
TableA
The time when it's not so good is ... - There is an index on the CoumntA website - Most values โโ(50% or more feel right) have exactly zero
In this case, two requests will be faster. This is because each query can use the index to quickly return home to the partition that needs to be counted. In the end, only counting the corresponding records.
However, the example I gave loops through the entire table every time. Only once, but always the entire table. It's worth it when you count most of the entries. In your case, it looks like what you think most or all of them are, and so this is probably a good way to do it.
source to share
This can be done in a single select statement.
How I did it before:
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 find it to be a very efficient way to do it.
Don't forget that you are not closing the case when ColumnA = 0
!
source to share
SELECT
SUM(IF(CoumntA < 0, 1, 0)) AS lowerThanZero,
SUM(IF(CoumntA > 0, 1, 0)) AS greaterThanZero
FROM
TableA
Is it clear what's going on? Ask if you have any more questions.
The shorter form would be
SELECT
SUM(CoumntA < 0) AS lowerThanZero,
SUM(CoumntA > 0) AS greaterThanZero
FROM
TableA
This is possible because in MySQL the true condition is 1, the false condition is 0
EDIT: ok ok ok sorry dont know why i thought of this here.
See other answers for correct syntax.
source to share
select '< 0' as filter, COUNT(0) as cnt from TableA where [condition 1]
union
select '> 0' as filter, COUNT(0) as cnt from TableA where [condition 2]
Make sure condition 1 and condition 2 create a section in the original recordset, otherwise the same records can be counted in both groups.
source to share