GROUP BY和多列中的唯一性

时间:2009-08-28 13:10:30

标签: sql mysql

让我们说我希望从几个连接表中选择3列:event_id,home_team和聚合函数的结果。 event_id是自动增加的主键。 home_team对于表中的每条记录都不是唯一的。我想按event_id分组以生成聚合函数,然后按聚合函数的结果排序,取最高的3个值。但我也希望home_team是独一无二的。我怎样才能做到这一点?我不能做DISTINCT因为记录会有home_team,event_id和聚合函数的结果。 event_id将始终是唯一的,因此我的DiSTINCT查询不执行任何操作。

我必须按event_id进行分组,因为聚合函数依赖于此,因此我无法按home_team进行分组。如果我按两者分组,它也无济于事,因为......

实施例

Table 1
  id: 1
  event_id: 1 
  value: 2

  id 2
  event_id: 1 
  value: 6

  id 3
  event_id: 2
  value: 4

  id4
  event_id: 2 
  value: 3

  id5
  event_id: 3
  value: 1

表2

event_id (PK, autoincremented): 1
home_team: 1

event_id: 2
home_team 2

event_id: 3
home_team: 1

SELECT *, AVG(table1.value) as average FROM table1 JOIN table2 ON table1.event_id = table2.event_id GROUP BY table2.event_id ORDER BY average DESC

我需要按table2.event_id分组才能生成正确的聚合函数结果。但是,我也希望home_team是不同的,所以期望的输出将是两个结果,event_id 1和event_id 2

2 个答案:

答案 0 :(得分:1)

好吧,按唯一键分组的聚合函数不会对你有多大帮助,这是肯定的。听起来你已经陷入了分组的想法,当你真正想要的只是每个home_team的三个最高价值的事件时。

尝试这样的事情,而不是:

select
    event_id,
    home_team,
    value
from
    my_tbl t
where
    event_id in 
        (select event_id from my_tbl 
         where home_team = t.home_team 
         order by value desc limit 0,3)

更新:您的编辑会清除一些内容,因此请执行以下操作:

select
    (select min(event_id) from table2 where home_team = t2.home_team) as event_id,
    t2.home_team,
    avg(t1.value) as average
from
    table1 t1
    inner join table2 t2 on
        t1.event_id = t2.event_id
group by
    t2.home_team

你所描述的是相当荒谬的。您想按event_id分组,但只显示一个home_team?除非您想要排在前面home_team行:

select
    home_team,
    max(average) as topavg
from
    (
    select
        t2.event_id,
        t2.home_team,
        avg(t1.value) as average
    from
        table1 t1
        inner join table2 t2 on
            t1.event_id = t2.event_id
    group by
        t2.event_id, t2.home_team
    ) as a
group by
    home_team

答案 1 :(得分:0)

使用此:

GROUP BY event_id, home_team

这将只分组具有相同event_id和相同home_team的记录。