一条sql语句分别统计出来两张表的数据

http://bbs.csdn.net/topics/380114638


come表,nocome表,分别有字段tid,然后我要从come表和nocome表分别统计出来tid的次数。统计的结果要是这样
|——————————————————————————————————————————————||
|   tid                          count(come.tid)                   count(nocome.tid)
|____________________________________________________________________________________________
|
|
|


select  tid, sum (a), sum (b)  from  (
select  tid, count (come.tid)  as  a,0   as  from  come  group  by  tid
union  all
select  tid,0  as  a, count (nocome.tid)  as  from  nocome  group  by  tid  order  by  tid)
group  by  tid  order  by  tid
 
 
create  table  come (
        tid number(10)
);
 
create  table  nocome(
        tid number(10)
);

==================================================================================

自测:

SELECT userid,sum(a),sum(b) from (
SELECT userid,count(app_customer.userid) as a,0 as b from app_customer GROUP BY userid
UNION all
SELECT userid,0 as a,count(app_product.userid) as b from app_product GROUP BY userid) as total GROUP BY userid
一条sql语句分别统计出来两张表的数据_第1张图片

合并 两个表的总数

SELECT userid,sum(a)+sum(b) from (
SELECT userid,count(app_customer.userid) as a,0 as b from app_customer GROUP BY userid
UNION all
SELECT userid,0 as a,count(app_product.userid) as b from app_product GROUP BY userid) as total GROUP BY userid

一条sql语句分别统计出来两张表的数据_第2张图片

再排一下序

一条sql语句分别统计出来两张表的数据_第3张图片

你可能感兴趣的:(一条sql语句分别统计出来两张表的数据)