如何将多列输出作为一列并找到该列的顶部

时间:2013-01-17 07:13:09

标签: php mysql sql database

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

这是我的查询:

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

此查询返回每列的平均值。但我只想选择前三名的平均值。

提前致谢!

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

希望这会有所帮助。 感谢