使用Union All进行oracle查询

时间:2016-02-26 07:29:46

标签: oracle

需要获得房间类型明智的女性和男性计数,以下是我的查询

 (SELECT  WARD,ROOMTYPE ,FEMALE,MALE
 FROM
(SELECT NS.WARD,RC.ROOMTYPE,(DECODE(IP.GENDER,'F',COUNT(IP.HNO)))FEMALE,(DECODE(IP.GENDER,'M',COUNT(IP.HNO)))MALE FROM BEDSHIFT R,BED B,NURSTATION NS,PATIENTS IP,ROOMTYPE RT,ROOMCATEGORY RC 
 WHERE R.BD_CODE=B.BD_CODE AND B.NS_CODE=NS.NS_CODE AND R.IP_NO=IP.IP_NO AND R.RMC_OCCUPBY='B' 
 AND B.RT_CODE=RT.RT_CODE AND RT.RC_CODE=RC.RC_CODE
 AND IP.IPC_STATUS IS NULL AND R.RMC_RELESETYPE IS NULL GROUP BY RC.ROOMTYPE,NS.WARD,IP.GENDER
UNION ALL
SELECT NS.WARD,RC.ROOMTYPE,(DECODE(IP.GENDER,'F',COUNT(IP.HNO)))FEMALE,(DECODE(IP.GENDER,'M',COUNT(IP.HNO)))MALE FROM PATIENTS IP,BED BD,NURSTATION NS,ROOMTYPE RT,ROOMCATEGORY RC  
 WHERE IP.BD_CODE=BD.BD_CODE 
 AND BD.RT_CODE=RT.RT_CODE AND RT.RC_CODE=RC.RC_CODE
 AND BD.NS_CODE=NS.NS_CODE AND IP.IPC_STATUS IS NULL GROUP BY RC.ROOMTYPE,NS.WARD,IP.GENDER)
  T 
 GROUP BY FEMALE,MALE,WARD,ROOMTYPE) ORDER BY WARD

返回

enter image description here

需要将其作为

enter image description here

2 个答案:

答案 0 :(得分:2)

只分组一次并对男性和女性求和:

SELECT WARD, ROOMTYPE, sum(FEMALE), sum(MALE)
  FROM (SELECT NS.WARD,
               RC.ROOMTYPE,
               IP.GENDER, 'F', COUNT(IP.HNO))) FEMALE,
               IP.GENDER, 'M', COUNT(IP.HNO))) MALE
          FROM BEDSHIFT     R,
               BED          B,
               NURSTATION   NS,
               PATIENTS     IP,
               ROOMTYPE     RT,
               ROOMCATEGORY RC
         WHERE R.BD_CODE = B.BD_CODE
           AND B.NS_CODE = NS.NS_CODE
           AND R.IP_NO = IP.IP_NO
           AND R.RMC_OCCUPBY = 'B'
           AND B.RT_CODE = RT.RT_CODE
           AND RT.RC_CODE = RC.RC_CODE
           AND IP.IPC_STATUS IS NULL
           AND R.RMC_RELESETYPE IS NULL
        UNION ALL
        SELECT NS.WARD,
               RC.ROOMTYPE,
               (DECODE(IP.GENDER, 'F', COUNT(IP.HNO))) FEMALE,
               (DECODE(IP.GENDER, 'M', COUNT(IP.HNO))) MALE
          FROM PATIENTS     IP,
               BED          BD,
               NURSTATION   NS,
               ROOMTYPE     RT,
               ROOMCATEGORY RC
         WHERE IP.BD_CODE = BD.BD_CODE
           AND BD.RT_CODE = RT.RT_CODE
           AND RT.RC_CODE = RC.RC_CODE
           AND BD.NS_CODE = NS.NS_CODE
           AND IP.IPC_STATUS IS NULL) T
 GROUP BY WARD, ROOMTYPE
 ORDER BY WARD

这样查询应该更快,而不是分组三次,甚至是四次。你也可以使用男性和女性的子查询,如果没有分组可以更快(没有看到模式,我不会给你查询)。

答案 1 :(得分:1)

更改第一行

(SELECT  WARD,ROOMTYPE ,SUM(FEMALE) AS FEMALE, SUM(MALE) AS MALE

和最后一行

GROUP BY WARD,ROOMTYPE) ORDER BY WARD,ROOMTYPE