什么查询会得到我这个结果?

时间:2013-11-03 21:47:16

标签: sql database postgresql

我有一张表格如下:

 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

3 个答案:

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

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

答案 2 :(得分:0)

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