SQL选择多个where子句

Ton*_*ony 1 sql sql-server

我正在尝试创建SQL Select,它根据字段返回某个字段的计数.所以,这就是我想要做的.

Select count(distinct id) as TotalCount, -- this will be the total of id
count(distinct id where type='A') as TotalA, -- this will be total when type='A'
count(distinct id where type='B') as TotalB -- This will be total when type = 'B'
from MyTable 
Run Code Online (Sandbox Code Playgroud)

基本上,TotalCount = TotalA + TotalB.

如何在SQL Select语句中实现此目的?谢谢.

Rem*_*anu 5

Select count(distinct id) as TotalCount, -- this will be the total of id
count(distinct case type when 'A' then id else NULL end) as TotalA,
count(distinct case type when 'B' then id else NULL end) as TotalB 
from MyTable;
Run Code Online (Sandbox Code Playgroud)

当然TotalCount可能是也可能不是TotalA + TotalB,具体取决于实际数据.