SQL:多个选择只有一个条件不同

时间:2016-10-20 08:40:40

标签: sql sql-server

我有一个初学者的问题。我的SQL表看起来像:

|   Date   | Type | Manufacturer |
2016/04/01    A         X
2016/04/01    B         Y
2016/04/02    B         X
2016/05/07    A         Z
  ...        ...       ...

我的目标是在两个日期之间计算制造商的“类型”数量。我想得到如下结果:

| Manufacturer | Quantity_TypeA | Quantity_TypeB |
   X               1                 1
   Y               0                 1
   Z               1                 0

我的查询如下:

 select Manufacturer as Manufacturer, 
 COUNT(*) as Quantity_TypeA
 From MyTable
 Where [Type] = 'A' and 
 Date between '20150101' and '20160930',
 COUNT(*) as Quantity_TypeB
 From MyTable 
 Where [Type] = 'B' and 
 Date between '20150101' and '20160930'    
 group by Manufacturer Order by Quantity_TypeA DESC

我还尝试在Type上使用CASE等函数,但它不起作用。我错过了什么,但是什么?

2 个答案:

答案 0 :(得分:2)

试试这个

select Manufacturer as Manufacturer, 
 SUM(case when [Type] = 'A' then 1 else 0 end) as Quantity_TypeA,
 SUM(case when [Type] = 'B' then 1 else 0 end) as Quantity_TypeB
 From MyTable
 Where 
 Date between '20150101' and '20160930'
group by Manufacturer 

答案 1 :(得分:1)

使用case表达式进行条件计数:

select Manufacturer as Manufacturer, 
       COUNT(case when [Type] = 'A' then 1 end) as Quantity_TypeA,
       COUNT(case when [Type] = 'B' then 1 end) as Quantity_TypeB
from MyTable
where Date between '20150101' and '20160930',
group by Manufacturer
order by Quantity_TypeA DESC

count()仅计算非空值。 case表达式返回1或null,即只计算A或B' s。