2011-01-07 61 views
0

你好
我有如下的MySQL表列:COND 額定值1,rating2,價格,覈定MYSQL不同條件

是否有可能選擇的結果是這樣的:

select 
average rating1 + rating2 as total_rating, 
average rating1 as rating1, 
average rating2 as rating2, 
average price if cond = '1' as price_used 
average price if cond = '2' as price_new 
where approved = '1' 

到目前爲止,我有:

SELECT 
(AVG(t.rating1) + AVG(t.rating2))/2 AS total_rating 
AVG(t.rating1) AS rating1, 
AVG(t.rating2) AS rating2, 
---- price statements?? ---- 
FROM t 
WHERE 1=1 
AND t.approved = '1' 

非常感謝,並原諒我的英語

回答

0

標準SQL,可以跨越 「所有」 主要DBMS:

select (avg(t.rating1) + avg(t.rating2))/2 as total_rating 
     ,avg(t.rating1) as rating1 
     ,avg(t.rating2) as rating2 
     ,avg(case when cond = '1' then price end) as price_used 
     ,avg(case when cond = '2' then price end) as price_new 
    from t 
where t.approved = '1' 
2

試試這個:

SELECT (AVG(t.rating1) + AVG(t.rating2))/2 AS total_rating, 
       AVG(t.rating1) AS rating1, 
       AVG(t.rating2) AS rating2, 
       AVG(IF(cond='1', price, NULL)) price_used, 
       AVG(IF(cond='2', price, NULL)) price_new 
FROM t 
WHERE 1=1 
AND t.approved = '1' 

編輯:更新了查詢以獲得期望的結果。

+0

不,它不工作,很遺憾。 price_used返回一個值,但絕對不是平均值,price_new返回0 – 2011-01-07 22:24:03

+0

您收到任何錯誤? – Chandu 2011-01-07 22:28:37

+0

沒有錯誤,但在price_new上出現空的結果,在price_used上出現錯誤的平均值 – 2011-01-07 22:30:08

0

我不認爲If語句的平均值會起作用。但是這裏是IF的語法。

IF(條件,value_to_display_if_true,value_to_display_if_false)

因此,舉例來說,IF(1 = 1, '真', '假')總是因爲1確實= 1顯示 '真' 此列。