SQL选择多个where子句

时间:2010-12-21 23:41:02

标签: 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 

基本上,TotalCount = TotalA + TotalB。

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

3 个答案:

答案 0 :(得分: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;

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

答案 1 :(得分:1)

你可以这样做:

SELECT
  count(distinct id) as TotalCount,
  sum(CASE WHEN type = 'A' THEN 1 ELSE 0) as TotalA,
  sum(CASE WHEN type = 'B' THEN 1 ELSE 0) as TotalB,
FROM
  MyTable 

按类型计算:

SELECT
  type,
  count(DISTINCT id)
FROM
  MyTable
GROUP BY
  type

答案 2 :(得分:0)

为什么不简单地将UNION作为单独的查询。

  Select 'all' as which, count(distinct id) as Total from mytable
  union 
  select 'a' as which, count(distinct id) where type='A' as Total from mytable
  union
  select 'b' as which, count(distinct id) where type='B' as Total from mytable