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

查询结果是sum有两个数据,我想请问怎么把两个数据加起来得到一个数据
SELECT count(*) as sum from hacconf.resource,hacconf.auditor_session_author,hacref.session where starttime>=1346169600 and starttime<=1346255999 and hacref.session.appname=hacconf.resource.name and hacconf.resource.dev_id=hacconf.auditor_session_author.dev_id and hacconf.auditor_session_author.manager_id=3 and endtime > 1 
UNION SELECT count(*) as sum from hacref.session where starttime>=1346169600 and starttime<=1346255999 and endtime = 1)

我的查询结果是sum有两个数据,我想请问怎么把两个数据加起来得到一个数据

------解决方案--------------------
要用union all,不要用union,因为union会过滤到重复的值。
SQL code

select (SELECT count(*)
        from hacconf.resource,hacconf.auditor_session_author,hacref.session 
        where starttime>=1346169600 and starttime<=1346255999 
        and hacref.session.appname=hacconf.resource.name 
        and hacconf.resource.dev_id=hacconf.auditor_session_author.dev_id 
        and hacconf.auditor_session_author.manager_id=3 and endtime > 1) 
    + 
        (SELECT count(*) from hacref.session 
        where starttime>=1346169600 and starttime<=1346255999 and endtime = 1)) as sum
--or
select sum(t.[sum]) as sum from 
(
    SELECT count(*) as sum
    from hacconf.resource,hacconf.auditor_session_author,hacref.session 
    where starttime>=1346169600 and starttime<=1346255999 
    and hacref.session.appname=hacconf.resource.name 
    and hacconf.resource.dev_id=hacconf.auditor_session_author.dev_id 
    and hacconf.auditor_session_author.manager_id=3 and endtime > 1
    union all
    SELECT count(*) from hacref.session 
    where starttime>=1346169600 and starttime<=1346255999 and endtime = 1
)t