简体   繁体   中英

SQL Server Select Statement Columns

Original Query:

select StudyID, count(CompletedDate), count(Removed), count(RemovalReason)
from Study a
full outer join Households b
on a.HouseholdID = b.HouseholdID
where StudyID = '123456'
and Removed = 1
and RemovalReason = 5
group by StudyID

How do I write out this query so that for each column (CompletedDate, Removed, and RemovalReason) is not restricted to the conditions (ie Removed = 1, Removal Reason = 5) and only applies to the specific column. If I execute this query, it will not show me the total count for CompletedDate because I'm restricting it to these conditions. Is there a way to write it directly next to count?

Table/Columns - Study: HouseholdID (primary key), StudyID, CompletedDate

Table/Columns - Households: HouseholdID (primary key), Removed, RemovalReason

I think you are looking for something like this, but your question is a little loose with details:

select StudyID
    , count(CompletedDate)
    , sum(case when Removed = 1 then 1 else 0 end)
    , sum(case when RemovalReason = 5 then 1 else 0 end)
from Study a
  join Households b
       on a.HouseholdID = b.HouseholdID
where StudyID = '123456'
group by StudyID

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