简体   繁体   English

计算属于同一列SQL Server的特定值

[英]Count specific values that belong to the same column SQL Server

I would like to ask for help I would like to count the number of records but having 2 conditions for 2 specific values only from a one single column: 我想寻求帮助,我想对记录的数量进行计数,但仅在一个列中就有2个条件用于2个特定值:

Count the records first: 首先计算记录:

count(service) as contacts 计数(服务)为联系人

service | state | address
service1| 1     |123
service2| 1     |321
service3| 3     |332
service1| 2     |333
service2| 2     |111
service3| 3     |333

1st result 第一个结果

Service | Contacts | status
service1| 1        | 1
service1| 1        | 2
service1| 1        | 3
service2| 1        | 1
service2| 1        | 2
service2| 1        | 3

if status = 1 and 2 then add to count else 0 (only count who's "status" is equal to 1 and 2. 如果status = 1和2,则将计数加到其他0(仅计算谁的“ status”等于1和2)。

Result: 结果:

Final result 最后结果

Service  | Contacts 
Service1 | 2       
Service2 | 2

sorry for the confusion Thanks for your big help 抱歉给您带来的混乱谢谢您的大力帮助

This should work for all major databases 这应该适用于所有主要数据库

SELECT service,
SUM(CASE WHEN status IN(1,2) THEN contacts ELSE 0 END) as Contacts
FROM (your query) as x
GROUP BY service
select service,
       sum(case when status in(1,2) then contacts else 0 end) as contact_count
from MyTable
group by service

What this will do is evaluate each row and include the contacts value in the sum where the status is one that is required. 这将对每一行进行评估,并在状态为必填状态的sum中包含contacts值。 As it is an aggregate, you need to group by the service 由于是汇总,因此您需要按service分组

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

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