[英]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. 我希望我的sql查询在一个日期或两个日期之间选择表中的所有字段,数据库中的3个字段的返回类型为bit。 This is somewhat my database looks
这有点像我的数据库
ID||Name || Surname || Age || Country || SumOfInfection || SumOfOtherInfection|| HasPersonContacted
SumOfInfection, SumOfOtherInfection& HasPersonContacted have the return type of bits. SumOfInfection,SumOfOtherInfection&HasPersonContacted具有位的返回类型。 For these three fields i;
对于这三个领域,我; need to sum the numbers of True(1) and False(0) into two separate columns.
需要将True(1)和False(0)的数量加到两个单独的列中。
Name|| 名称|| Surname||
姓|| .... ||HasPersonContacted(sum of 1's based on a userID) ||
.... || HasPersonContacted(1的和基于用户ID)|| HasPersonContacted(sum of 0's based on a userID) ..... so what i am looking for
HasPersonContacted(基于用户ID为0的总和).....所以我在找什么
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 . 我想对SumOfOtherInfection和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? 这是我所做的,但仅显示SumOfInfection的总和。我如何一次性获得所有这些数据? i rely like to use Select * because in future if i am looking for more data i dont have to rewrite my query.
我依靠使用Select *,因为将来如果我要查找更多数据,则不必重写查询。
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()
: 尝试使用条件
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.