oracle 三表关联查询

左连接实现三表关联

表A---------------------------------关联第一张表B-----------------------关联第二张表c

1.语法

  select * from 表名A left join 表B on A.columnX=B.columnM and A.columnY=B.columnN left join 表c on 表A=表c的id

2.应用场景

  四张表 GJPT_BASY、GJZY_BASY、GJPT_BASY_ERROR、GJZY_BASY_ERROR
  根据四张表,要求返回:医疗机构名称,医疗机构编号,总数,合格数和问题数

3.SQL实现

SELECT TEMP1.*, TEMP2.HEGESUM, TEMP3.TROUBLESUM
  FROM (SELECT T1.YLNAME, T1.YLCODE, SUM(RS1) AS YLSUM--总数
      FROM (SELECT COUNT(1) AS RS1,
               HDSD00_11_118 AS YLNAME,
               HDSD00_11_119 AS YLCODE
          FROM GJPT_BASY
         GROUP BY HDSD00_11_119, HDSD00_11_118
        UNION ALL
        SELECT COUNT(1) AS RS1,
               HDSD00_12_133 AS YLNAME,
               HDSD00_12_134 AS YLCODE
          FROM GJZY_BASY
         GROUP BY HDSD00_12_133, HDSD00_12_134
        UNION ALL
        SELECT COUNT(1) AS RS1,
               HDSD00_11_118 AS YLNAME,
               HDSD00_11_119 AS YLCODE
          FROM GJPT_BASY_ERROR
         GROUP BY HDSD00_11_119, HDSD00_11_118
        UNION ALL
        SELECT COUNT(1) AS RS1,
               HDSD00_12_133 AS YLNAME,
               HDSD00_12_134 AS YLCODE
          FROM GJZY_BASY_ERROR
         GROUP BY HDSD00_12_133, HDSD00_12_134) T1
     GROUP BY T1.YLNAME, T1.YLCODE) TEMP1
  LEFT JOIN (SELECT *
           FROM (SELECT T2.YLNAME, T2.YLCODE, SUM(RS2) AS HEGESUM--合格数
               FROM (SELECT COUNT(1) AS RS2,
                    HDSD00_11_118 AS YLNAME,
                    HDSD00_11_119 AS YLCODE
                   FROM GJPT_BASY
                  GROUP BY HDSD00_11_119, HDSD00_11_118
                 UNION ALL
                 SELECT COUNT(1) AS RS2,
                    HDSD00_12_133 AS YLNAME,
                    HDSD00_12_134 AS YLCODE
                   FROM GJZY_BASY
                  GROUP BY HDSD00_12_133, HDSD00_12_134) T2
              GROUP BY T2.YLNAME, T2.YLCODE)) TEMP2
    ON TEMP2.YLNAME = TEMP1.YLNAME
   AND TEMP2.YLCODE = TEMP1.YLCODE
  LEFT JOIN (SELECT *
           FROM (SELECT T3.YLNAME, T3.YLCODE, SUM(RS3) TROUBLESUM--问题数
               FROM (SELECT COUNT(1) AS RS3,
                    HDSD00_11_118 AS YLNAME,
                    HDSD00_11_119 AS YLCODE
                   FROM GJPT_BASY_ERROR
                  GROUP BY HDSD00_11_119, HDSD00_11_118
                 UNION ALL
                 SELECT COUNT(1) AS RS3,
                    HDSD00_12_133 AS YLNAME,
                    HDSD00_12_134 AS YLCODE
                   FROM GJZY_BASY_ERROR
                  GROUP BY HDSD00_12_133, HDSD00_12_134) T3
              GROUP BY T3.YLNAME, T3.YLCODE)) TEMP3
    ON TEMP3.YLNAME = TEMP1.YLNAME
   AND TEMP3.YLCODE = TEMP1.YLCODE
   WHERE TEMP3.YLCODE='41580781841010511A1001';

 

posted @ 2018-07-04 17:55  Marydon  阅读(13005)  评论(0编辑  收藏  举报