I have a postgis table with point geometries.
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?
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.
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.
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 .
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With