选择按 id

时间:2021-05-05 09:37:42

标签: sql oracle oracle11g oracle-apex

在我的代表汽车服务站的数据库中,我试图找出一个 SQL 查询,该查询将为我提供客户为单项服务支付的总平均费用,而不是获取价格的 AVG()在所有现有发票上,我想按相同的reservation_id 对发票进行分组。之后,我想获得所有这些分组结果的总平均值。

我正在使用下图中列出的两个表。我想通过对通过相同 FK Reservation_reservation_id 对价格进行分组而得出的所有平均值应用 AVG() 来获得总平均价格的值。

enter image description here

我试图将它变成一个单一的查询,但我失败了,所以我向更有经验的用户寻求帮助。另外,我只需要选择(获取)总平均值的结果。这个结果应该能让我大致了解每位客户为一次预订支付的平均费用。

感谢您的时间

3 个答案:

答案 0 :(得分:1)

您似乎想要聚合两次:

SELECT AVG( avg_price ) avg_avg_price
FROM   (
  SELECT AVG( price ) AS avg_price
  FROM   invoice
  GROUP BY reservation_reservation_id
)

对于样本数据:

CREATE TABLE invoice ( reservation_reservation_id, price ) AS
SELECT 1, 10 FROM DUAL UNION ALL
SELECT 1, 12 FROM DUAL UNION ALL
SELECT 1, 14 FROM DUAL UNION ALL
SELECT 1, 16 FROM DUAL UNION ALL
SELECT 2, 10 FROM DUAL UNION ALL
SELECT 2, 11 FROM DUAL UNION ALL
SELECT 2, 12 FROM DUAL;

输出:

<块引用>
<头>
AVG_AVG_PRICE
12

db<>fiddle here

答案 1 :(得分:1)

如果您希望每个客户都这样做:

SELECT customer_customer_id, AVG(avg_reservation_price)
FROM (SELECT i.customer_customer_id, i.reservation_reservation_id, 
             AVG(i.price) as avg_reservation_price
      FROM invoice i
      GROUP BY i.customer_customer_id, i.reservation_reservation_id
     ) ir
GROUP BY customer_customer_id;

如果您出于特定的“结帐原因”需要此服务——这是我想象的最接近“服务”的意思——然后加入预订表并过滤:

SELECT customer_customer_id, AVG(avg_reservation_price)
FROM (SELECT i.customer_customer_id, i.reservation_reservation_id, 
             AVG(i.price) as avg_reservation_price
      FROM invoice i JOIN
           reservation r
           ON i.reservation_reservation_id = r.reservation_id
      WHERE r.checkup_type = ?
      GROUP BY i.customer_customer_id, i.reservation_reservation_id
     ) ir
GROUP BY customer_customer_id;

答案 2 :(得分:0)

您可能想尝试以下操作:

with aux (gr, subgr, val) as (
    select 'a', 'a1', 1 from dual union all
    select 'a', 'a2', 2 from dual union all
    select 'a', 'a3', 3 from dual union all
    select 'a', 'a4', 4 from dual union all
    select 'b', 'b1', 5 from dual union all
    select 'b', 'b2', 6 from dual union all
    select 'b', 'b3', 7 from dual union all
    select 'b', 'b4', 8 from dual)
SELECT
    gr, 
    avg(val) average_gr,
    avg(avg(val)) over () average_total
FROM
    aux
group by gr;

应用于您的表,将导致:

SELECT
    reservation_id, 
    avg(price) average_rn,
    avg(avg(price)) over () average_total
FROM
    invoices
group by reservation_id;