按月统计sql脚本(access版本+oracle版本)

七海恋空 2014-12-28 浏览(0 评论(0

access版本 

按月统计数据主要用到iff函数和sum函数。iff函数用的比较少,说明一下:iff(<条件>,<条件为真返回值>,<条件为假返回值>)。sum函数主要是来计算iff函数返回值的总和。

select c.channel,
sum(iif (month(a.setdate)=1,1,0) )as jan,
sum(iif (month(a.setdate)=2,1,0) )as feb,
sum(iif (month(a.setdate)=3,1,0) )as mar,
sum(iif (month(a.setdate)=4,1,0) )as apr,
sum(iif (month(a.setdate)=5,1,0) )as may,
sum(iif (month(a.setdate)=6,1,0) )as jun,
sum(iif (month(a.setdate)=7,1,0) )as jul,
sum(iif (month(a.setdate)=8,1,0) )as aug,
sum(iif (month(a.setdate)=9,1,0) )as sep,
sum(iif (month(a.setdate)=10,1,0) )as oct,
sum(iif (month(a.setdate)=11,1,0) )as nov,
sum(iif (month(a.setdate)=12,1,0) )as dece from (computer a inner join user b on a.userid=b.userid)inner join channel c on c.channelcode=b.channelcode where year(a.setdate)=year(now()) group by c.channel

注意事项:1.在access中联合查询语句要加括号,很是蛋疼。2.还有直接复制代码的别换行。3.其中dec是保留字,所以十二月的英文缩写改成dece,个人一直认为用英文比较高大上,用拼音的真够土的。

oracle版本 

oracle跟access一样有专门抽取年月日的函数。extract函数居然还能抽取时分秒,这倒没试过。原先不知道有这个函数,查询时间周期一直用between,and,todate(),真不是一般的复杂。这里case语句代替了access中的iff函数,应该也很好理解。 

select c.channel as 部门,
sum(case when extract(month from a.setdate)=1 then 1 else 0 end) as "1月",
sum(case when extract(month from a.setdate)=2 then 1 else 0 end) as "2月",
sum(case when extract(month from a.setdate)=3 then 1 else 0 end) as "3月",
sum(case when extract(month from a.setdate)=4 then 1 else 0 end) as "4月",
sum(case when extract(month from a.setdate)=5 then 1 else 0 end) as "5月",
sum(case when extract(month from a.setdate)=6 then 1 else 0 end) as "6月",
sum(case when extract(month from a.setdate)=7 then 1 else 0 end) as "7月",
sum(case when extract(month from a.setdate)=8 then 1 else 0 end) as "8月",
sum(case when extract(month from a.setdate)=9 then 1 else 0 end) as "9月",
sum(case when extract(month from a.setdate)=10 then 1 else 0 end) as "10月",
sum(case when extract(month from a.setdate)=11 then 1 else 0 end) as "11月",
sum(case when extract(month from a.setdate)=12 then 1 else 0 end) as "12月" from  computer a inner join user b on a.userid=b.userid inner join channel c on c.channelcode=b.channelcode where extract(year from a.setdate)=2014 group by c.channel