-2

我有一张如下表:

 att1 |  att2  |  num           
------+--------+------+
 wm1    | A |    1
 wm6    | A |    3
 wm5    | B |    4
 wm7    | C |    2
 wm0    | D |    1
 wm2    | D |    2
 wm3    | D |    2
 wm4    | E |    1

我想要一个结果,它给我每个 att2 的最大数量。什么查询会给我下表?

 att1 |  att2  |  num           
------+--------+------+
 wm6    | A |    3
 wm5    | B |    4
 wm7    | C |    2
 wm2    | D |    2
 wm3    | D |    2
 wm4    | E |    1

编辑:我试过:

SELECT att2, max(num) FROM *original table* GROUP BY att2

但这会返回:

 att2  |  num           
------+--------+
 | A |    3
 | B |    4
 | C |    2
 | D |    2
 | D |    2
 | E |    1
4

3 回答 3

2

这应该有效:

SELECT t1.att1, t1.att2, t1.num 
FROM table1 t1
INNER JOIN (SELECT att2, max(num) AS max_num FROM Table1 GROUP BY att2
  ) t2 ON t1.att2=t2.att2 AND t1.num = t2.max_num
ORDER BY t1.att2, num

使用 PostgreSQL 9.2.4 的示例SQL Fiddle 。

于 2013-11-03T22:04:21.247 回答
1
select att1, att2, num
from (
  select att1, 
         att2, 
         num,
         max(num) over (partition by att2) as max_num
  from the_table
) t
where num = max_num;
于 2013-11-03T22:06:54.877 回答
0

试试SELECT att1, att2, MAX(num) as num FROM table GROUP BY att2 ORDER BY att2 ASC ;

于 2013-11-03T21:59:48.503 回答