联表根据共同字段分组sql统计数据

简单的连表统计某个ID出现的次数则sql类似:
select t2.*,( select count(t1.id) from cook_comment t1 where t1.goodsId=t2.id ) as commentNumber  from goods  t2 ;

涉及到多列需要作为查询分组的如下示例:sql联表查询根据共同字段group by分组统计数据并显示,

行数据:

select a.*, t.starttime, t.endtime
  from (select l.jobid,
               l.kddate,
               sum(l.count) updateTimes,
               sum(decode(l.status, 2, 1, 0)) failTimes,
               sum(l.cost) totalCost,
               sum(l.rowsize) updateSize
          from kdgs_realtime_log l
        -- where l.kddate = 20171017
        --   and l.jobId = 1000009
        --and l.status = 2
         group by l.jobid, l.kddate) a,
       kdgs_qrtz_trigger_info t
 where t.id = a.jobid

如果只需要查询某条ID对应的数据则需要把相关where注释打开。

汇总信息低效率的方式是不用group by而是逐一查询各数据再展示,如下

select * from kdgs_realtime_log t where t.jobid = 1000009;
select i.id,i.starttime,i.endtime,
(select sum(l.count) from kdgs_realtime_log l where l.jobid=i.id and l.kddate=20171018) as updateTimes,
(select count(1) from kdgs_realtime_log l where l.jobid=i.id and l.kddate=20171018 and l.status=2) as failTimes,
(select sum(l.cost) from kdgs_realtime_log l where l.jobid=i.id and l.kddate=20171018) as totalCost,
(select sum(l.rowsize) from kdgs_realtime_log l where l.jobid=i.id and l.kddate=20171018) as updateSize
 from kdgs_qrtz_trigger_info i where i.id=1000009;


 

猜你喜欢

转载自blog.csdn.net/u010760374/article/details/81114454
今日推荐