I have a table like;
CREATE TABLE public.user_locations
(
id integer NOT NULL DEFAULT nextval('user_locations_id_seq'::regclass),
user_id integer,
created_at timestamp without time zone,
location geography(Point,4326),
cluster_id integer,
CONSTRAINT user_locations_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
CREATE INDEX index_user_locations_on_location
ON public.user_locations
USING gist
(location);
CREATE INDEX index_user_locations_on_user_id
ON public.user_locations
USING btree
(user_id);
I would like to get minimum and maximum created_at values for each cluster for a specific user. So that i will see how long the user stayed in a cluster.
Currently i do this;
SELECT * FROM (
(
SELECT DISTINCT ON (cluster_id) * FROM user_locations
WHERE user_id = 6
ORDER BY cluster_id, created_at DESC
)
UNION
(
SELECT DISTINCT ON (cluster_id) * FROM user_locations
WHERE user_id = 6
ORDER BY cluster_id, created_at ASC
)
) a
ORDER BY cluster_id, created_at
I think this is not a good solution. Is this the right query for my problem? If not could you suggest better ways to retrieve the minimum and maximum values for each cluster for a specific user?