1

テーブルの各列の平均を選択しているシナリオで行き詰まりました。次に、これらの列の上位3つを見つけたいと思います。

これが私の質問です:

SELECT AVG( `adventure` ) , AVG( `beach` ) , AVG( `culture` ) , AVG( `festival` ) , AVG( `food` ) , AVG( `fun` ) , AVG( `biking` ) , AVG( `ski` ) , AVG( `surf` ) , AVG( `family` ) , AVG( `couple` ) , AVG( `single` ) , AVG( `backpacker` )
FROM `ratings`
WHERE `reference_id`=4595

このクエリは、各列の平均を返します。ただし、上位3つの平均のみを選択したいと思います。

前もって感謝します!

4

2 に答える 2

3

最初にテーブルを正規化する必要があると思いますが、ニーズに合ったクエリを次に示します。

ちなみに、平均が計算された列の名前と平均の結果の2つの列が返されます。

SELECT  Category, avgVal
FROM
    (
        SELECT  'adventure' AS Category, AVG(`adventure`) AS avgVal FROM `ratings` WHERE `reference_id`=4595
        UNION
        SELECT  'beach' AS Category, AVG(`beach`)  AS avgVal FROM `ratings` WHERE `reference_id`=4595
        UNION
        SELECT  'culture' AS Category, AVG(`culture`)  AS avgVal FROM `ratings` WHERE `reference_id`=4595 
        UNION
        SELECT  'festival' AS Category, AVG(`festival`)  AS avgVal FROM `ratings` WHERE `reference_id`=4595 
        UNION
        SELECT  'food' AS Category, AVG(`food`)  AS avgVal FROM `ratings` WHERE `reference_id`=4595
        UNION
        SELECT  'fun' AS Category, AVG(`fun`)  AS avgVal FROM `ratings` WHERE `reference_id`=4595 
        UNION
        SELECT  'biking' AS Category, AVG(`biking`)  AS avgVal FROM `ratings` WHERE `reference_id`=4595 
        UNION
        SELECT  'ski' AS Category, AVG(`ski`)  AS avgVal FROM `ratings` WHERE `reference_id`=4595 
        UNION
        SELECT  'surf' AS Category, AVG(`surf`)  AS avgVal FROM `ratings` WHERE `reference_id`=4595 
        UNION
        SELECT  'family' AS Category, AVG(`family`)  AS avgVal FROM `ratings` WHERE `reference_id`=4595 
        UNION
        SELECT  'couple' AS Category, AVG(`couple`)  AS avgVal FROM `ratings` WHERE `reference_id`=4595 
        UNION
        SELECT  'single' AS Category, AVG(`single`)  AS avgVal FROM `ratings` WHERE `reference_id`=4595 
        UNION
        SELECT  'backpacker' AS Category, AVG(`backpacker`)  AS avgVal FROM `ratings` WHERE `reference_id`=4595 
    ) s
ORDER BY avgVal DESC
LIMIT 3
于 2013-01-17T07:22:58.263 に答える
0

ここでサブクエリを使用する必要があります

 SELECT AVG( `adventure` ) 
       ,AVG( `beach` )
       ,AVG( `culture` )
       , AVG( `festival` )
       , AVG( `food` )
       , AVG( `fun` )
       , AVG( `biking` )
       , AVG( `ski` )
       , AVG( `surf` )
       , AVG( `family` )
       , AVG( `couple` )
       , AVG( `single` )
       , AVG( `backpacker` ) 
FROM ( SELECT adventure,beach,culture,festival,food,fun,biking,ski,surf,family,couple,single,backpacker
       FROM `ratings`
       WHERE `reference_id`=4595 
       LIMIT 0,3
) DerivedTable

お役に立てれば。ありがとう

于 2013-01-17T07:24:32.180 に答える