2015-09-04 158 views
0

我有一張表;PostgreSQL,Groupwise最小值和最大值

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); 

我想獲得的最小和最大created_at值爲每個集羣爲特定用戶。這樣我就會看到用戶在羣集中停留了多久。

目前我這樣做;

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 

我認爲這不是一個好的解決方案。這是對我的問題正確的查詢?如果不是,您能否提出更好的方法來爲特定用戶檢索每個羣集的最小值和最大值?

回答

2

這是窗函數是:

select id, user_id, cluster_id, location, 
     created_at, 
     min(created_at) over (partition by cluster_id) as min_created, 
     max(created_at) over (partition by cluster_id) as max_created 
    from user_locations 
    where user_id = 6 
    order by cluster_id, created_at 
+0

對不起,此方法返回USER_ID = 6 –

+0

添加的所有行:「上(CLUSTER_ID)獨特的」開始的選擇,返回正確的結果。感謝您的好消息。 –

+0

請編輯您的答案,以便我可以接受它作爲答案。另一件事是;我的索引是否正確?你可以檢查並推薦一些提示,如果可能的話? –