在sql中的同一个表上的单个语句中的多个计数语句

时间:2014-04-14 13:05:39

标签: sql

如何将这两个查询合并为一个查询?我尝试了各种选项,但没有一个可行。

SQL>

select count (*) from tab_proclog_cso where ( to_char(starttime, 'yyyymmddhh24miss') between('20130709000000') and ('20130709010000') );

  COUNT(*)
----------
     28328

SQL>

select count (*) from tab_proclog_cso where ( to_char(starttime, 'yyyymmddhh24miss') between('20130709010000') and ('20130709020000') );

  COUNT(*)
----------
     14997

3 个答案:

答案 0 :(得分:1)

select 
   sum(case when to_char(starttime, 'yyyymmddhh24miss') between('20130709000000') and ('20130709010000') then 1 else 0 end) as res1
   ,sum(case when to_char(starttime, 'yyyymmddhh24miss') between('20130709000000') and ('20130709010000') then 1 else 0 end) as res2
from tab_proclog_cso 

答案 1 :(得分:0)

你可以做一个UNION,这将产生两行:

select count (*) AS COL from tab_proclog_cso where ( to_char(starttime, 'yyyymmddhh24miss')    
between('20130709000000') and ('20130709010000') )
UNION
select count (*) AS COL from tab_proclog_cso where ( to_char(starttime, 'yyyymmddhh24miss') 
between('20130709010000') and ('20130709020000') )

或为单行执行2个计算列:

SELECT
(select count (*) from tab_proclog_cso where ( to_char(starttime, 'yyyymmddhh24miss')    
between('20130709000000') and ('20130709010000') ) ) AS COL1,
( select count (*) from tab_proclog_cso where ( to_char(starttime, 'yyyymmddhh24miss') 
between('20130709010000') and ('20130709020000') ) ) AS COL2

或总计:

SELECT
(select count (*) from tab_proclog_cso where ( to_char(starttime, 'yyyymmddhh24miss')    
between('20130709000000') and ('20130709010000') ) ) +
( select count (*) from tab_proclog_cso where ( to_char(starttime, 'yyyymmddhh24miss') 
between('20130709010000') and ('20130709020000') ) ) AS TOTAL

答案 2 :(得分:0)

    select count (*) as count1,(select count (*) from tab_proclog_cso where ( 
to_char(starttime, 'yyyymmddhh24miss') between('20130709010000')
 and ('20130709020000') )) count2 from tab_proclog_cso where ( to_char(starttime,    
'yyyymmddhh24miss') between('20130709000000') and ('20130709010000') );

我想这对你有用