在MySQL中,我有这个查询/表
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 :(得分: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
答案 1 :(得分:0)
您所谈论的内容可以使用简单的OAF(有序分析功能)来完成:
SELECT foo.*
,AVG(rating) OVER (ORDER BY id ASC) AS rating
FROM my_table AS foo
WHERE bar = /* many crazy shitz */
这将为整个表提供AVG
函数,分布在所有行中。