简体   繁体   English

选择Count Where大于0 SQL Server的值

[英]Select Count Where Values greater than 0 SQL Server

I'm trying to figure out how to return a select query showing a count of all values in a column that are greater than 0. Then in the next column show a count of all values that = 0. 我试图弄清楚如何返回一个选择查询,显示列中所有值的计数大于0.然后在下一列中显示所有值的计数= 0。

Example: 例:

ID  ColumnA
1   1    
2   2
3   1
4   2
5   0
6   0
7   1

Would return a result for the select query of: 将返回选择查询的结果:

NumberOfGreaterThan0    NumberThatEqual0

5                       2

You can use conditional aggregates for this via CASE expression: 您可以通过CASE表达式为此使用条件聚合:

SELECT COUNT(CASE WHEN ColumnA > 0 THEN 1 END) AS NumberOfGreaterThan0 
      ,COUNT(CASE WHEN ColumnA = 0 THEN 1 END) AS NumberThatEqual0
FROM YourTable

This works because aggregate functions ignore NULL values. 这是有效的,因为聚合函数会忽略NULL值。

You can use a couple of count functions over case expressions: 您可以在case表达式上使用几个count函数:

SELECT COUNT(CASE WHEN columa > 0 THEN 1 ELSE NULL END) AS NumberOfGreaterThan0,
       COUNT(CASE columa WHEN 0 THEN 1 ELSE NULL END) AS NumberThatEqual0
FROM   my_table

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM