带联接表的Oracle SQL group by

1bqhqjot  于 12个月前  发布在  Oracle
关注(0)|答案(1)|浏览(112)

我有三张table


的数据




我希望获取APPT_NO、APPT_DATETIME、PATIENT_NO、PATIENT_FULL_NAME、TOTAL_COST,其中总费用等于一个预约记录的最大总费用
在APPT_SERV中,可以有多个行具有相同的APPT_NO
我是这么做的,但这是错误的

SELECT APPT_NO, APPT_DATETIME, PATIENT_NO, 
       (CASE WHEN NVL (PATIENT_FNAME, 'NULL') != 'NULL' THEN PATIENT_FNAME || ' ' ELSE '' END) || PATIENT_LNAME AS PATIENT_FULL_NAME,
       NVL(SUM(APPTSERV_FEE), 0) + NVL(SUM(APPTSERV_ITEMCOST), 0) + NVL(SUM(SERVICE_STDFEE), 0) AS TOTAL_COST
FROM APPOINTMENT
JOIN PATIENT USING(PATIENT_NO)
JOIN APPT_SERV USING(APPT_NO)
JOIN SERVICE USING(SERVICE_CODE)
WHERE NVL(SUM(APPTSERV_FEE), 0) + NVL(SUM(APPTSERV_ITEMCOST), 0) + NVL(SUM(SERVICE_STDFEE), 0) = 
    (SELECT MAX(NVL(SUM(APPTSERV_FEE), 0) + NVL(SUM(APPTSERV_ITEMCOST), 0) + NVL(SUM(SERVICE_STDFEE), 0))
    FROM APPOINTMENT
    JOIN APPT_SERV USING(APPT_NO)
    JOIN SERVICE USING(SERVICE_CODE)
    GROUP BY APPT_NO);

字符串

mzillmmw

mzillmmw1#

这个怎么样?阅读代码中的注解。
我删除了所有使代码难以阅读的东西(NVL函数调用,CASE表达式,... -稍后包括它们)。

WITH
   appt_cost
   AS
      -- calculate total cost per each appointment and sort rows by total cost in descending order
      (  SELECT s.appt_no,
                SUM (s.apptserv_fee + s.apptserv_itemcost + s.service_stdfee)
                   AS total_cost,
                RANK ()
                   OVER (
                      ORDER BY
                         SUM (s.apptserv_fee + s.apptserv_itemcost + s.service_stdfee) DESC)
                   rn
           FROM appt_serv s
       GROUP BY s.appt_no)
-- fetch all other data you need
SELECT a.appt_no,
       a.appt_datetime,
       a.patient_no,
       p.patient_fname,
       c.total_cost
  FROM patient  p
       JOIN appointment a ON a.patient_no = p.patient_no
       JOIN appt_cost c ON c.appt_no = a.appt_no
 -- return row(s) whose total cost is equal to the highest total cost (i.e. one(s) that ranked as the highest)
 WHERE c.rn = 1;

字符串

相关问题