SQL查询和子查询

时间:2015-11-05 16:59:40

标签: mysql subquery

我对所有SQL专家都有疑问。

有桌子看起来像:

 clanname  country     points
 name1     country1    100
 name2     country1    90
 name3     country1    10
 name4     country2    100
 name5     country2    80
 name6     country2    70

我想做一个国家排名只涉及每个国家的前2名结果。所以,在这个例子中,排名应该是:

 country    average-points
 country2   95
 country1   90

如果使用子查询只有一个SQL查询可以获得此结果吗?

实际上,我有200多个国家......每个国家都有数千个结果。但我想只过滤每个国家的前30个结果。

现在我设法使用此查询获得一个国家/地区的平均值:

  SELECT 
      location, AVG(warswon)
  FROM
      (SELECT 
           `name`, `location`, `warswon` 
       FROM 
           `clans`
       WHERE 
           location = 'China'
       ORDER BY 
           `clans`.`warswon` DESC 
       LIMIT 30) AS top30ofcountry

但如何在一个查询中获得每个国家/地区的平均结果?

这可能吗?

2 个答案:

答案 0 :(得分:2)

这是每组问题。在使用row_number的许多DB中,这是微不足道的。在MySQL中,您可以使用用户变量

来完成
SELECT 
  country ,
  avg(points)
FROM
(
  SELECT 
        @num := if(@group = `country`, @num + 1, 1) as row_number,
        @group := `country` as dummy,
        clanName,
        country,
        points
    FROM
      clans
      JOIN (SELECT @group := NULL, @num := 0) as z
     order by
        country, points desc) as x 
WHERE x.row_number <=2 
GROUP BY 
    country

答案 1 :(得分:0)

感谢康拉德的帮助。 我设法通过稍微改变你提出的代码来获得reqested结果。 以下是有类似问题的人的最终工作查询:

SELECT 
location,
avg(warswon)
FROM
(
SELECT 
@num := if(@group = `location`, @num + 1, 1) as row_number,
@group := `location` as dummy,
name,
location,
warswon
FROM
clans
JOIN (SELECT @group := NULL, @num := 0) as z
order by
location, warswon desc
) as x 
WHERE x.row_number <= 30
GROUP BY `location`
ORDER BY avg(warswon) DESC