简体   繁体   English

使用SQL Server 2008的select语句中具有条件的聚合函数

[英]Aggregation function with condition in select statement using SQL Server 2008

I have following table: 我有下表:

create table test
(
 cola integer
)

With some data: 有一些数据:

cola
-------
0
1
0
2
0
3
0
4
0
5

Here I need to count number of zero's presents in the cola , and also want to sum number of other values which are greater than 0, like sum(1,2,3,4,5) . 在这里,我需要count cola存在的零的数量,还想对大于0的其他值的数量sum(1,2,3,4,5) ,例如sum(1,2,3,4,5)

My bad try: 我的错误尝试:

select count(cola) as zeros ,sum(cola) as others
from test
where cola = 0 and cola > 0;

You want conditional aggregation: 您需要条件聚合:

select sum(case when cola = 0 then 1 else 0 end) as zeros,
       sum(case when cola > 0 then cola else 0 end) as others
from test;

Strictly speaking, the second conditional is not needed, assuming the values are never negative: 严格来说,假设值永远不会为负,则不需要第二个条件:

select sum(case when cola = 0 then 1 else 0 end) as zeros,
       sum(cola) as others
from test;

this query will count number of zero's presents in the cola, and also sum number of other values which are greater than 0, like sum(1,2,3,4,5) 此查询将计算可乐中存在的零的数量,以及其他大于0的其他值的总和,例如sum(1,2,3,4,5)

Answer: 回答:

select 
count (case when cola=0 then cola end) as Zeros,
sum (case when cola>0 then cola end) as otherthanzeroes
from test;

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

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