日期:2014-05-17  浏览次数:20785 次

看看这个按年/月/日汇总的SQL效率如何
数据库结构为: userName varchar
  loginTime timestamp

需求是能够对登录用户进行按年、按月、按日三种时间粒度的查询,我写了一个SQL语句如下,不知道效率能否怎么再改进,请教高手。

按年汇总:
SQL code
select userName, to_date(to_char(LOGINTIME, 'yyyy'), 'yyyy') period, count(*) from EOSADMINLOGINTRACE group by userName, to_date(to_char(LOGINTIME, 'yyyy'), 'yyyy') order by to_date(to_char(LOGINTIME, 'yyyy'), 'yyyy');

按月汇总:
SQL code
select userName, to_date(to_char(LOGINTIME, 'yyyy-MM'), 'yyyy-MM') period, count(*) from EOSADMINLOGINTRACE group by userName, to_date(to_char(LOGINTIME, 'yyyy-MM'), 'yyyy-MM') order by to_date(to_char(LOGINTIME, 'yyyy-MM'), 'yyyy-MM');

按天汇总
SQL code
select userName, to_date(to_char(LOGINTIME, 'yyyy-MM-dd'), 'yyyy-MM-dd') period, count(*) from EOSADMINLOGINTRACE group by userName, to_date(to_char(LOGINTIME, 'yyyy-MM-dd'), 'yyyy-MM-dd') order by to_date(to_char(LOGINTIME, 'yyyy-MM-dd'), 'yyyy-MM-dd');


------解决方案--------------------
都转换了2次..

substr(LOGINTIME,1,4)
substr(LOGINTIME,1,6)
substr(LOGINTIME,1,8)
------解决方案--------------------
时间大的对应截取的字符肯定也会大 效果应该一样
------解决方案--------------------
时间大的对应截取的字符肯定也会大 效果应该一样
------解决方案--------------------
直接trunc就可以了,不用转来转去