MySQL SELECT n基于GROUP BY记录

时间:2011-01-14 06:55:08

标签: sql mysql group-by greatest-n-per-group

让我说我有SQL记录:

Country | Number
USA | 300
USA | 450
USA | 500
USA | 100
UK  | 300
UK  | 400
UK  | 1000

我正在做这样的事情:SELECT * FROM table GROUP BY Country 如果,我想选择仅在每个国家/地区显示2个最大数字的结果,该怎么办?我该如何存档?

结果将是:

Country | Number
USA | 450
USA | 500
UK  | 400
UK  | 1000

3 个答案:

答案 0 :(得分:2)

示例数据

create table data (Country varchar(10), Number int);
insert into data select
'USA' , 300 union all select
'USA' , 450 union all select
'USA' , 500 union all select
'USA' , 100 union all select
'FR'  , 100 union all select
'FR'  , 420 union all select
'UK'  , 300 union all select
'UK'  , 400 union all select
'UK'  , 1000;

第一个选项是使用Scrum Meister所显示的变量的伪等级,但在此处显示为单个陈述

SELECT Country, Number
FROM (
    SELECT
        Number,
        @r := case when @c=country then @r+1 else 1 end rownum,
        @c := Country Country 
    FROM (select @r :=0 , @c := '') x, data
    ORDER BY Country, Number DESC
) y
WHERE rownum < 3;

如果您在前端使用它,并且只需要2个计数,那么您可以使用此表单返回列表中的计数(单列)

SELECT
    Country,
    left(x,locate(',',concat(x,','),locate(',',x)+1)-1) Numbers
FROM (
    SELECT
        a.Country,
        Group_Concat(a.Number) x
    From (
        select country, number
        from data
        order by country, number desc) a
    group by a.Country
) b

结果是

"Country";"Numbers"
"FR";"420,100"
"UK";"1000,400"
"USA";"500,450"

如果有可能发生关系,那么第二种形式的这种变化将删除关系并显示“每个国家的前2个不同数字”,作为记录。

SELECT distinct x.Country, x.Number
From data x
inner join
(
    SELECT
        Country,
        left(x,locate(',',concat(x,','),locate(',',x)+1)-1) Numbers
    FROM (
        SELECT
            a.Country,
            Group_Concat(a.Number) x
        From (
            select distinct country, number
            from data
            order by country, number desc) a
        group by a.Country
    ) b
) y on x.Country=y.Country
    and concat(',',y.Numbers,',') like concat('%,',x.Number,',%')
order by x.Country, x.Number Desc

结果

"Country";"Number"
"FR";"420"
"FR";"100"
"UK";"1000"
"UK";"400"
"USA";"500"
"USA";"450"

答案 1 :(得分:1)

由于MySql没有内置的RANK函数,查询可能会很慢:

SET @cRank = 0;
SET @cCoutnry = '';

SELECT Country, Number
FROM (
    SELECT Number, @cRank := IF(@cCoutnry = Country, @cRank+1, 1) AS rank, @cCoutnry := Country Country 
    FROM table
    ORDER BY Country, Number DESC
) rs
WHERE rank < 3

答案 2 :(得分:0)

让我们将你的表命名为TName,然后他们会查询。

SELECT * FROM (SELECT ROW_NUMBER() OVER (PARTITION BY X.Country) AS RowNo, *
FROM (SELECT Country, Name FROM TName ORDER BY Country, Number) X ) Y WHERE Y.RowNo <= 2