简体   繁体   English

计算所有列的平均值,然后计算输出差异

[英]Calculate Average for all columns and then output difference

Hello i am having some trouble determining what is wrong with my query. 您好,我在确定查询错误时遇到了一些麻烦。

I am trying to output the average cost of all events unrelated to the Event name. 我试图输出与事件名称无关的所有事件的平均成本。 However when processing my query a connection seems to be made between the event name and the average. 但是,在处理我的查询时,似乎在事件名称和平均值之间建立了连接。 I believe the query is generating the average cost of each event related to that name not the total average. 我相信查询会生成与该名称相关的每个事件的平均成本,而不是总平均值。 Once i have the average i want to then display only the events that cost beyond the average cost price. 一旦我有了平均值,我想只显示超出平均成本价格的事件。

Query: 查询:

SELECT Event_Name AS 'Event Name'
              ,ROUND(Event_Cost) AS 'Event Cost'
              ,ROUND(AVG(Event_Cost)) AS 'Average Cost Of Events'
              ,ROUND(Event_Cost - AVG(Event_Cost)) AS 'Amount Over Average £'
FROM Event
WHERE Event_Cost > (SELECT AVG(Event_Cost) FROM Event)
GROUP BY Event_Name;

I am sure it is something really simple i am missing. 我确信这是一件非常简单的事情。 Thanks in advance 提前致谢

There are two problems in your query. 您的查询中存在两个问题。 The first one is that since you're selecting the event_name, your average is calcluated at that level; 第一个是因为您选择了event_name,所以您的平均值会在该级别进行计算; the other problem is that you're using the Event_Cost column both as is and aggregated at the same time, from the same table, and that's not possible. 另一个问题是,您在同一个表中同时使用Event_Cost列并进行聚合,而这是不可能的。

You should get the aggregated value from an inner query and cross join it with your initial table, like this 您应该从内部查询中获取聚合值,并将其与初始表交叉连接,如下所示

SELECT  t1.Event_Name AS 'Event Name',
        ROUND(Event_Cost) AS 'Event Cost',
        ROUND(t2.aver) AS 'Average Cost Of Events',
        ROUND(Event_Cost - t2.aver) AS 'Amount Over Average £'
FROM    Event t1
CROSS JOIN
        (
            SELECT  AVG(Event_cost) as aver
            FROM    Event
        ) t2
WHERE   t1.Event_Cost > t2.aver;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM