2013-12-18 157 views
2

我有一個包含ID字段和3個日期時間字段的表。我需要得到每個日期時間字段monthwise.I的數量正在使用按日期時間字段分組

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 

然後我複製這導致到Excel和下面設置數據:

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

我在想,如果有一種方式我可以結合這三個查詢,而不是一次寫入一次查詢?

回答

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 –

相關問題