使用聚合函数进行过滤

时间:2015-09-16 08:49:40

标签: sql postgresql postgis

我想通过MIN()函数过滤我的表格,但仍保留不能分组的列。

我有桌子:

+----+----------+----------------------+
| ID | distance |         geom         |
+----+----------+----------------------+
|  1 | 2        | DSDGSAsd23423DSFF    |
|  2 | 11.2     | SXSADVERG678BNDVS4   |
|  2 | 2        | XCZFETEFD567687SDF   |
|  3 | 24       | SADASDSVG3423FD      |
|  3 | 10       | SDFSDFSDF343DFDGF    |
|  4 | 34       | SFDHGHJ546GHJHJHJ    |
|  5 | 22       | SDFSGTHHGHGFHUKJYU45 |
|  6 | 78       | SDFDGDHKIKUI45       |
|  6 | 15       | DSGDHHJGHJKHGKHJKJ65 |
+----+----------+----------------------+

这就是我想要实现的目标:

+----+----------+----------------------+
| ID | distance |         geom         |
+----+----------+----------------------+
| 1  |        2 | DSDGSAsd23423DSFF    |
|  2 |        2 | XCZFETEFD567687SDF   |
|  3 |       10 | SDFSDFSDF343DFDGF    |
|  4 |       34 | SFDHGHJ546GHJHJHJ    |
|  5 |       22 | SDFSGTHHGHGFHUKJYU45 |
|  6 |       15 | DSGDHHJGHJKHGKHJKJ65 |
+----+----------+----------------------+

我可以在距离列上使用MIN()并按ID进行分组,但随后我会丢失必不可少的geom。

查询如下所示:

SELECT "ID", MIN(distance) AS distance FROM somefile GROUP BY "ID" 

结果是:

+----+----------+
| ID | distance |
+----+----------+
| 1  |        2 |
|  2 |        2 |
|  3 |       10 |
|  4 |       34 |
|  5 |       22 |
|  6 |       15 |
+----+----------+

但这不是我想要的。

有什么建议吗?

4 个答案:

答案 0 :(得分:1)

一种常见的方法是在您加入的派生表中找到最小值:

Array
(
    [0] => Array
        (
            [id] => 123
            [name] => Alex
            [count] => 2
        )

    [1] => Array
        (
            [id] => 124
            [name] => John
            [count] => 2
        )

    [2] => Array
        (
            [id] => 126
            [name] => Paul
            [count] => 1
        )

)

Sample SQL Fiddle

答案 1 :(得分:0)

您需要一个窗口功能来执行此操作:

SELECT "ID", distance, geom
FROM (
  SELECT "ID", distance, geom, rank() OVER (PARTITION BY "ID" ORDER BY distance) AS rnk
  FROM somefile) sub
WHERE rnk = 1;

这有效地将整个行集按"ID"值排序,然后按距离排序并返回距离最小的每个"ID"的记录 - 无需执行{{1 }}

答案 2 :(得分:0)

select a.*,b.geom from
(SELECT ID, MIN(distance) AS distance FROM somefile  GROUP BY ID) as a
inner join somefile  as b on a.id=b.id and a.distance=b.distance

答案 3 :(得分:0)

你可以使用" distinct" PostgreSQL的子句。

select distinct on(id) id, distance, geom from table_name order by distance;

我认为这正是你所寻找的。

有关如何"区别于"的详细信息。有效,请参考documentation and the example

但是,请记住,使用" distinct"不符合SQL标准。