1、临时表的联表查询
在sql查询中,经常碰到问题是一次查询select无法完成所有想要的数据。这时候可以划分成查询多次生成多个临时表,再联表处理。例如,我们有个初始表:
现在我们要根据开始时间t1和结束时间t2,生成一张表。
其中,service_type 表示列表,count表示这个列表的总量,increment表示在t1,t2这时间段指定类别的量。这个结果没法一次select完成,因为,全量count和增量increment无法同时在一次select完成。我们的核心思想是查两次生成两张表后,联结表。sql语句如下:
select table_a.service_type, table_a.count, table_b.increment from (select service_type, count(*) as count from qq_mds_tran_log group by service_type) table_a, (select service_type,count(*) as increment from qq_mds_tran_log where statis_date > '20160810' and statis_date<'20160815' group by service_type) table_b where table_a.service_type = table_b.service_type;
语句select service_type, count(*) as count from qq_mds_tran_log group by service_type;用于生成表table_a;
语句select service_type,count(*) as increment from qq_mds_tran_log where statis_date > '20160810' and statis_date<'20160815' group by service_type;用于生成表table_b;