sql的强大功能(看一条sql解决的复杂业务)

    一条sql语句解决的复杂业务,请往下看:

    业务介绍:一个单位有多个立项(立项信息表里有单位id),每个立项可能被预警多次(预警信息表里的uuid字段的值里包含有立项id或单位id),每个预警事件又可能被督办多次(督办信息表里有预警id),最后需要统计出每个单位一年被督办的总次数(total)

    查询涉及的表有:立项表(special_task)、预警事件表(alarm_event)、预警被督办信息表(alarm_action_status_history)

    Sql语句:如下图所示

      

SELECT
  st.create_dept as dept_id
, count(*) as total
  FROM  yujing.special_task st
  right join yujing.alarm_event ae on ae.event_uuid like concat('zxjc\_4\_',st.create_dept)
                                   or ae.event_uuid like concat('zxjc\_4\_',st.id,'\_%')
  right join yujing.alarm_action_status_history ash
    on ash.risk_event_id = ae.id
   and ash.old_status in (2010,2020)
   and ash.new_status = 2020
   and ash.change_time >= '2013-01-01'
   and ash.change_time <= '2013-12-31'
 WHERE  st.create_dept = 34
        and st.type = 22
        and st.create_time >= '2013-01-01'
        and st.create_time <= '2013-12-31'

    总结:sql语句写好了不但能实现复杂的业务,还能提高程序的执行效率,而且还能让我们的程序逻辑变的更加简单,平时我们应该在这方便多下点功夫,这样做会给我们带来更高的效益、更多的鼓励。


原文地址:https://www.cnblogs.com/pangblog/p/3278521.html