联表根据共同字段分组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分组统计数据并显示,

联表根据共同字段分组sql统计数据_第1张图片

联表根据共同字段分组sql统计数据_第2张图片

行数据:

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;


 

你可能感兴趣的:(数据库与SQL)