2014-07-07 72 views
1

在MySQL中,我有這樣的查詢/表AVG()不進行分組

SELECT * 
FROM 
(
    SELECT 
     id, 
     (SELECT MY_FUNCTION(id)) AS rating -- Function returns a float 
    FROM my_table 
    WHERE 
    /* Very long WHERE */ 
) AS ratings 

id    rating 
----------  ------------- 
1    1.00 
2    2.00 
3    10.00 
4    11.05 
5    10.04 

現在,我試圖讓avereage評級

SELECT *, AVG(rating) 
FROM 
(
    SELECT 
     id, 
     (SELECT MY_FUNCTION(id)) AS rating -- Function returns a float 
    FROM my_table 
    WHERE 
    /* Very long WHERE */ 
) AS ratings 

id    rating   AVG(rating) 
----------  ------------- ------------- 
1    1.00   6,818 

因爲AVG()是一個聚合函數,其他線條被剝離。我想(不喜歡here)保持這樣的線,沒有做另一個選擇my_table,因爲WHERE太複雜,做兩次。就像這樣:

id    rating   AVG(rating) 
----------  ------------- ------------- 
1    1.00   6,818 
2    2.00   6,818 
3    10.00   6,818 
4    11.05   6,818 
5    10.04   6,818 

我也試過這樣:Using SUM() without grouping the results,但我不能讓CROSS JOIN與表的別名或沒有做複雜的WHERE部分兩次工作。

+0

http://dba.stackexchange.com/questions/40130/mysql-and-window-functions –

回答

1

我會使用臨時表。

CREATE TEMPORARY TABLE Ratings (
ID Int Not Null, 
Rating Float Not Null 
) 
Insert Ratings (ID, Rating) 
Select ID, MyFunction(ID) 
From my_table 
--Where yaadddyaddd 

Declare @Average float 
Select @Average = Avg(Rating) From Ratings 
Select ID, Rating, @Average 
+0

完成此操作,非常感謝。 –

0

你在談論可以用一個簡單的OAF(有序分析功能)做些什麼:

SELECT foo.* 
    ,AVG(rating) OVER (ORDER BY id ASC) AS rating 
FROM my_table AS foo 
WHERE bar = /* many crazy shitz */ 

這會給你整個表格的AVG功能,在所有行傳播。

+0

mysql是否有窗口函數? –

+0

哦,噓,我沒有看到MySQL的一部分。該死的。 – PlantTheIdea

+0

那麼沒有其他選擇? ;)臨時表是可能的,但似乎有點矯枉過正 –