簡體   English   中英

如何用位返回類型對1和0進行計數,並在兩個單獨的列中將其返回

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

我希望我的sql查詢在一個日期或兩個日期之間選擇表中的所有字段,數據庫中的3個字段的返回類型為bit。 這有點像我的數據庫

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

SumOfInfection,SumOfOtherInfection&HasPersonContacted具有位的返回類型。 對於這三個領域,我; 需要將True(1)和False(0)的數量加到兩個單獨的列中。

名稱|| 姓|| .... || HasPersonContacted(1的和基於用戶ID)|| 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

我想對SumOfOtherInfection和HasPersonContacted做同樣的事情。

這是我所做的,但僅顯示SumOfInfection的總和。我如何一次性獲得所有這些數據? 我依靠使用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' 

嘗試使用條件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' ;

或者,您可以將該位轉換為整數:

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

編輯:

我認為完整的查詢更像是:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM