2013-12-18 2 views
2

ID 필드와 3 datetime 필드가있는 테이블이 있습니다. 이 경우 궁금 해서요Group Datetime 필드로

Month  CountID(datetime1) CountID(datetime2) CountID(datetime3) 
June-2013 50     20     16 
July-2013 24     10     56 

을 : 나는 그럼이 엑셀에 결과를 복사하고 아래와 같이 데이터를 설정

Select to_char(datatime1,'Mon-yyyy'),count(id) from table 
where datetime1 is not null 

Select to_char(datatime2,'Mon-yyyy'),count(id) from table 
where datetime2 is not null 

Select to_char(datatime3,'Mon-yyyy'),count(id) from table 
where datetime3 is not null 

을 사용하고 각 날짜 시간 필드 monthwise.I의 수를 얻을 필요 한 번에 한 번씩 쿼리를 작성하는 대신 세 가지 쿼리를 결합 할 수있는 방법은 무엇입니까?

답변

1

가입

select p , sum(cnt1) as cnt1 , sum(cnt2) as cnt1 , sum(cnt3) as cnt3 
from (select to_char(datetime1,'Mon-yyyy') as p , 
       count(id)      as cnt1 , 
       0        as cnt2 , 
       0        as cnt3 
     from table 
     where datetime1 is not null 
     group by to_char(datetime1,'Mon-yyyy') 
     UNION ALL 
     select to_char(datetime2,'Mon-yyyy') as p , 
       0        as cnt1 , 
       count(id)      as cnt2 , 
       0        as cnt3 
     from table 
     where datetime2 is not null 
     group by to_char(datetime2,'Mon-yyyy') 
     UNION ALL 
     select to_char(datetime3,'Mon-yyyy') as p , 
       0        as cnt1 , 
       0        as cnt2 , 
       count(id)      as cnt3 
     from table 
     where datetime2 is not null 
     group by to_char(datetime2,'Mon-yyyy') 
    ) t 
group by t.p 
order by t.p 

또는 틀림없이 단순 노동 조합을 시도 + 왼쪽 :

select to_char(t.dt,'Mon-yyyy') as period , 
     sum(case when t1.id is not null then 1 else 0 end) as cnt1 , 
     sum(case when t2.id is not null then 1 else 0 end) as cnt2 , 
     sum(case when t3.id is not null then 1 else 0 end) as cnt3 
from (select datetime1 as dt from table where datetime1 is not null 
     UNION 
     select datetime2 as dt from table where datetime2 is not null 
     UNION 
     select datetime3 as dt from table where datetime3 is not null 
    ) t 
left join table t1 on t1.datetime1 = t.dt 
left join table t2 on t2.datetime2 = t.dt 
left join table t3 on t3.datetime3 = t.dt 
group by to_char(t.dt,'Mon-yyyy') 

그것을 하나 개 이상의 방법이있다.

+0

+1 나는 답을 달기 위해 바이올린을하고 있었지만, 처음부터 해 봤는데 ... http://sqlfiddle.com/#!4/d0e9d/3 –

+1

고마워! 위대한 마음은 똑같이 생각합니다 : D –