2016-10-25 36 views
0

我對MSSQL語句有一些疑問。所以基本上這是我的SQL查詢:WHERE子句中的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); 

我所試圖做的是子查詢裏,我每個用戶平均獲取最新組的列表。返回的例子數據(用戶名,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每個用戶,所以我不能簡單地選擇平均。

任何想法如何解決這個問題?

在此先感謝。

+0

什麼是錯誤訊息? –

+0

錯誤消息是聚合可能不會出現在WHERE子句中,除非它位於包含在HAVING子句或選擇列表中的子查詢中,並且要聚合的列是外部引用。我試圖做的是在子查詢中,我得到每個用戶的平均日組列表。然後在外部查詢中,我從列表中獲取最小值。任何想法如何實現這一目標? – hyperfkcb

+0

是的。但爲了簡單起見,我刪除了它。我甚至重命名了列名,就好像我要使用我的原始表名一樣,這會很混亂 – hyperfkcb

回答

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); 
+0

對不起,但avg_date列未被識別。此外,在第二條語句的最後一個括號中有語法錯誤 – hyperfkcb

+0

您有任何想法嗎? – hyperfkcb

+0

在外部查詢中嘗試「擁有」insted「where」。 – Nitin