트릭은 아래 그림과 같이 자신의 테이블에 다시 가입하는 것입니다. myTable as A
은 Good
행만 읽고 myTable as B
행은 Bad
행만 읽습니다. 그런 다음 행은 date
을 기반으로 signle 행에 가입됩니다.
SQL Fiddle Demo
select
a.date
,a.count as Good_count
,b.count as bad_count
,a.count-b.count as diff_count
from myTable as a
inner join myTable as b
on a.date = b.date and b.type = 'Bad'
where a.type = 'Good'
출력 반환
DATE GOOD_COUNT BAD_COUNT DIFF_COUNT
March, 03 2014 00:00:00+0000 100 15 85
March, 04 2014 00:00:00+0000 120 10 110
또 다른 aproach 대신 inner join
의 Group by
을 사용하는 것입니다 :
select
a.date
,sum(case when type = 'Good' then a.count else 0 end) as Good_count
,sum(case when type = 'Bad' then a.count else 0 end) as Bad_count
,sum(case when type = 'Good' then a.count else 0 end) -
sum(case when type = 'Bad' then a.count else 0 end) as Diff_count
from myTable as a
group by a.date
order by a.date
두 가지 접근법이 동일한 결과를 생성합니다.
정확히 2 줄이 있습니까, 1. Good & 2. Bad, 각 날짜마다? –