2015-03-31 178 views
1

我已經使用以下子句創建了表VQ1。無法使用查看錶中的平均聚合數

CREATE VIEW VQ1 as 
SELECT productid, productname, TO_CHAR(unitprice,'$9,999.99') AS "unitprice"  
    FROM products 
WHERE unitprice > avg(unitprice) 
    WITH READ ONLY; 

我收到一個錯誤消息,我無法使用聚合函數AVG()來查找平均值。

那麼我怎樣才能找到AVG()的觀點?

回答

2

你可以試試這個隊友:

CREATE VIEW VQ1 AS 
SELECT 
    productid, 
    productname, 
    TO_CHAR(unitprice, '$9,999.99') 'unitprice' 
FROM 
    products 
GROUP BY 
    productid 
HAVING 
    unitprice > AVG(unitprice); 
+0

我所指的單位價格不是引用的單位價格,可以想象它將一個非數字字段平均值進行比較。然後編輯,@DavidFaber – Avidos 2015-03-31 05:54:06

+0

標記被改變了,它有'mysql'之前,這就是爲什麼我試圖回答它。那麼,忘掉它吧。 – Avidos 2015-04-01 05:20:33

+0

@DavidFaber已經選中了綠色,並且你親David – 2015-04-01 08:36:47

0

由於avg是一個集合函數,因此它不能在select中使用,除非在group by子句中指定了其他字段。

create view VQ1 as 
select productid, productname, 
TO_CHAR(unitprice,'$9,999.99') as "unitprice" 
from products, 
(select avg(unitprice) as avgprice from products) 
where unitprice > avgprice 
with read only; 
+0

據我所知,子查詢是不是在創建視圖使用。 http://dev.mysql.com/doc/refman/5.5/en/view-restrictions.html – Avidos 2015-03-31 00:50:48

+0

所以,如果我們想在一個除group by子句之外的地方使用聚合函數,我們必須將它放在分號之間? – 2015-03-31 00:52:55

+0

@Avidos - 我在引用的文章中找不到限制,只限制視圖中FROM子句中的相關替代項......「FROM子句中的子查詢不能關聯子查詢,它們在整體中被實現(評估爲產生一個結果集)在評估外部查詢之前,所以它們不能在外部查詢的每一行進行評估。「 – 2015-03-31 01:01:02

-1

你可以用窗口(分析)完成這一功能:

CREATE VIEW vq1 AS 
SELECT productid, productname, unitprice FROM (
    SELECT productid, productname, unitprice, AVG(unitprice) OVER() AS avg_unitprice 
     FROM products 
) WHERE unitprice > avg_unitprice 
    WITH READ ONLY; 
+0

爲什麼downvote? – 2015-04-01 12:04:21

相關問題