聯表根據共同字段分組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;


 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章