如何在内部查询的外部查询中进行算术运算

时间:2014-02-23 21:41:03

标签: sql ms-access

我是SQL的新手,我正在尝试在访问中构建查询。我需要选择两列小于平均比率的比率。 我能够首先对数据进行分组,以便能够获得每列的总数。我还能够得到以下各组的比率(查询有效):

SELECT col1, Ratio
FROM (
    SELECT ID, SUM(col3)/SUM(col4) AS Ratio 
    FROM table1 
    GROUP BY ID
)  AS Ratios 
INNER JOIN table2 
ON Ratios.ID=table2.ID

但是,我想仅显示那些小于平均比率的比率。我用另一种方式尝试了,我收到一条消息:“无法在WHERE子句中聚合函数”

SELECT col1, Ratio
FROM (
    SELECT ID, SUM(col3)/SUM(col4) AS Ratio 
    FROM table1 
    GROUP BY ID
)  AS Ratios 
INNER JOIN table2 
ON Ratios.ID=table2.ID
WHERE Ratio<AVG(Ratio)

任何人都可以帮我看看我做错了什么,我一直在研究这个问题几个小时,说实话,我在这里不知所措。

1 个答案:

答案 0 :(得分:1)

这在Access中是一个痛苦的查询。你可以这样做:

SELECT col1, Ratio
FROM (SELECT ID, SUM(col3)/SUM(col4) AS Ratio 
      FROM table1 
      GROUP BY ID
     )  AS Ratios INNER JOIN
     table2 
     ON Ratios.ID = table2.ID
WHERE Ratio < (select AVG(Ratio)
               from (SELECT ID, SUM(col3)/SUM(col4) AS Ratio 
                     FROM table1 
                     GROUP BY ID
                    ) as t
              );

编辑:

是的,您可以使用having子句执行此操作,但必须将其嵌入子查询中:

SELECT col1, Ratio
FROM (SELECT ID, SUM(col3)/SUM(col4) AS Ratio 
      FROM table1 
      GROUP BY ID
      HAVING SUM(col3)/SUM(col4) < (select AVG(Ratio)
                                    from (SELECT ID, SUM(col3)/SUM(col4) AS Ratio 
                                          FROM table1 
                                          GROUP BY ID
                                         ) as t
                                   )
     )  AS Ratios INNER JOIN
     table2 
     ON Ratios.ID = table2.ID;