2016-10-20 3 views
-1

초급 질문이 있습니다.SQL : 하나의 조건 만 다른 다중 선택

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

내 목표는 두 날짜 사이에 제조업체의 "유형"의 양을 계산하는 것입니다처럼 내 SQL 테이블 보인다. 나는 다음과 같은 결과를 얻을 싶습니다

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 

가 나는 또한 유형에 CASE와 같은 기능을 사용하려고하고 그것은 작동하지 않았다 같은

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

내 쿼리 보인다. 나는 무엇인가 놓치고있다. 그러나 무엇?

+0

이 보인다보십시오. 열 날짜의 데이터 유형? – jarlh

답변

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

이것은 완벽합니다! – Elhendriks

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()

는 null 이외의 값을 계산 않습니다. case 표현식은 1 또는 null을 반환합니다. 즉 A 또는 B 만 계산됩니다.