Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order grouped rows before aggregate function

I have a postgis table with point geometries.

points table:

id | uid | date | geom

Points with the same uid are the same target. I'm trying to GROUP BY uid with the ST_MakeLine to create a complete target LineString.

SELECT uid, ST_MakeLine(geom)
FROM points
GROUP BY uid

This works, but I want to make sure the points are in the correct order. I tried doing this by adding an ORDER BY date before grouping.

SELECT uid, ST_MakeLine(geom)
FROM points
ORDER BY date <-- does not work
GROUP BY uid

ERROR: syntax error at or near "GROUP"

Is there a way to order the grouped rows before they are fed into the aggregate function?

like image 982
Ilia Choly Avatar asked Feb 18 '14 16:02

Ilia Choly


People also ask

Do aggregate functions apply to groups of rows?

Group functions are mathematical functions to operate on sets of rows to give one result per set. The types of group functions (also called aggregate functions) are: AVG, that calculates the average of the specified columns in a set of rows, COUNT, calculating the number of rows in a set.

Can you order by aggregate function?

An aggregate function cannot be used directly in: an ORDER BY clause. Attempting to do so generates an SQLCODE -73 error. However, you can use an aggregate function in an ORDER BY clause by specifying the corresponding column alias or selectItem sequence number.

Does aggregate functions need GROUP BY?

If you don't specify GROUP BY , aggregate functions operate over all the records selected. In that case, it doesn't make sense to also select a specific column like EmployeeID .

Can you order by SUM SQL?

Use ORDER BY if you want to order rows according to a value returned by an aggregate function like SUM() . The ORDER BY operator is followed by the aggregate function (in our example, SUM() ). DESC is placed after this function to specify a descending sort order.


2 Answers

The ORDER BY clause can be placed at the end of the aggregate arguments.

SELECT uid, ST_MakeLine(geom ORDER BY date)
FROM points
GROUP BY uid

http://www.postgresql.org/docs/9.1/static/sql-expressions.html#SYNTAX-AGGREGATES

like image 80
Ilia Choly Avatar answered Oct 04 '22 00:10

Ilia Choly


Maybe have the data you want ordered in a temp table, and then group externally by uid?

 SELECT uid, ST_MakeLine(geom)
 FROM
 (
    SELECT uid, geom
    FROM points
    ORDER BY date
 ) AS temp
 GROUP BY uid
like image 45
gts Avatar answered Oct 03 '22 22:10

gts