WHERE子句中的SQL查询聚合函数

时间:2016-10-25 06:40:38

标签: sql-server sql-server-2008 select subquery

我对MSSQL语句有一些疑问。所以基本上这是我的SQL查询:

SELECT table1.col1, avg(datediff(dd, table2.date, table3.date)) as avg_date
INNER JOIN table2
INNER JOIN table3
WHERE avg_date <= ALL
(SELECT table1.col1, avg(datediff(dd, table2.date, table3.date)) as avg_date
INNER JOIN table2
INNER JOIN table3
GROUP BY table1.col1);

我想要做的是在子查询中,我得到每个用户的平均日期组列表。返回的示例数据是(userName,avg_date):

user1  10
user2  20
user3  20

然后,在外面的查询中,我需要找到从子查询返回的平均日期的最小值。但是,通过执行此操作,我从外部查询获取和错误消息,我只比较1列,子查询返回2列。

错误讯息为An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference

但是,在我的子查询中,我需要每个用户使用GROUP BY,所以我不能简单地选择平均值。

任何想法如何解决这个问题?

提前致谢。

1 个答案:

答案 0 :(得分:2)

试试这个

SELECT table1.col1, avg(datediff(dd, table2.date, table3.date)) as avg_date
INNER JOIN table2
INNER JOIN table3
HAVING avg_date <= (SELECT avg_date from
(SELECT table1.col1, avg(datediff(dd, table2.date, table3.date)) as avg_date
INNER JOIN table2
INNER JOIN table3
GROUP BY table1.col1)
);

替代:

SELECT * FROM
(
    SELECT table1.col1, avg(datediff(dd, table2.date, table3.date)) as avg_date
    INNER JOIN table2
    INNER JOIN table3
) outer_table
WHERE avg_date <= ALL(SELECT avg_date from(SELECT table1.col1,avg(datediff(dd, table2.date, table3.date)) as avg_date
INNER JOIN table2
INNER JOIN table3
GROUP BY table1.col1));

为SQL Server编辑

SELECT * FROM
(
    SELECT table1.col1, avg(datediff(dd, table2.date, table3.date)) as avg_date
    INNER JOIN table2
    INNER JOIN table3
) outer_table
WHERE avg_date <= ALL(SELECT inner_table.avg_date from
(SELECT table1.col1,avg(datediff(dd, table2.date, table3.date)) as avg_date
INNER JOIN table2
INNER JOIN table3
GROUP BY table1.col1) inner_table);