简体   繁体   中英

How count the 1's and 0's with a bit return type and return it in two separate columns

I would like my sql query to select all the fields in a table by one date or between two dates, 3 of the fields in my database have the return type as bits. This is somewhat my database looks

ID||Name || Surname || Age || Country || SumOfInfection || SumOfOtherInfection|| HasPersonContacted

SumOfInfection, SumOfOtherInfection& HasPersonContacted have the return type of bits. For these three fields i; need to sum the numbers of True(1) and False(0) into two separate columns.

Name|| Surname|| .... ||HasPersonContacted(sum of 1's based on a userID) || HasPersonContacted(sum of 0's based on a userID) ..... so what i am looking for

SumOfInfection <- all the 1's for that ID
output= 10 <- so the person had 10 infection
SumOfInfection <- all the 0's for that ID
output= 3 - so the person had no infection for 3 times

i would like to do same for SumOfOtherInfection and HasPersonContacted .

This is what i have done but it only shows the sum of SumOfInfection how do i get all these data in one go? i rely like to use Select * because in future if i am looking for more data i dont have to rewrite my query.

SELECT COUNT(NULLIF(SumOfInfection,1)) 
From [TableName] 
where ID='1234' AND Cast([Time] AS DATE) >'2012-01-09' AND CAST([Time] AS DATE) < '2014-01-01' 

Try using conditional sum() :

SELECT sum(case when SumOfInfection = 1 then 1 else 0 end) as NumInfection1,
       sum(case when SumOfInfection = 0 then 1 else 0 end) as NumInfection0
From [TableName] 
where ID='1234' AND Cast([Time] AS DATE) >'2012-01-09' AND CAST([Time] AS DATE) < '2014-01-01' ;

Alternatively, you can cast the bit as an integer:

SELECT sum(cast(SumOfInfection as int)) as NumInfection1,
       sum(1 - cast(SumOfInfection as int)) as NumInfection1

EDIT:

I think the full query is more like:

select Name, Surname,
       sum(case when HasPersonContacted = 1 then 1 else 0 end) as NumPersonContacted1,
       sum(case when HasPersonContacted = 0 then 1 else 0 end) as NumPersonContacted0,
       . . .
from t
group by Name, Surname;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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