1

我陷入了一个场景,我选择了表格中每一列的平均值。现在我想找到这些列中的前三列。

这是我的查询:

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

我想你需要先规范化你的表,但这里有一个适合你需要的查询,

顺便说一下,它返回两列,计算平均值的列的名称和平均值的结果。

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 回答