聚合+最后&第一 - >失去秩序

时间:2018-06-11 15:02:25

标签: sql postgresql aggregate-functions

我正在尝试在15分钟的步进间隔内选择数据。主要的分组接缝按预期工作,但我在每个15分钟组内失去秩序。原因是例如:    对于4个点,其中time_stamp在0-14分钟范围内 - > “floor(EXTRACT(分钟来自time_stamp)/ 15)AS quarter”,将返回值“0”(如预期的那样)。 那么ORDER BY“quarter”4用“quarter”==“0”的行,从中选择最后一个和第一个值。 这导致了我无法保证基于时间戳的排序的情况。

SELECT
    first(value) as first_value,
    last(value) as last_value,
    CAST(EXTRACT(year FROM time_stamp) AS INTEGER) AS year,
    CAST(EXTRACT(month FROM time_stamp) AS INTEGER) AS month,
    CAST(EXTRACT(day FROM time_stamp) AS INTEGER) AS day,
    CAST(EXTRACT(hour FROM time_stamp) AS INTEGER) AS hour,
    floor(EXTRACT(minute FROM time_stamp) / 15) AS quarter,
FROM
    my_table
GROUP BY
    year,
    month,
    day,
    hour,
    quarter,
ORDER BY
    year,
    month,
    day,
    hour,
    quarter

下面是表格示例:

CREATE TABLE my_table (
    id integer NOT NULL,
    time_stamp timestamp without time zone NOT NULL,
    value double precision NOT NULL,
);


CREATE SEQUENCE my_table_id_seq
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


ALTER TABLE ONLY my_table ALTER COLUMN id SET DEFAULT nextval('my_table_id_seq'::regclass);


ALTER TABLE ONLY my_table
    ADD CONSTRAINT my_table_pkey PRIMARY KEY (id);


CREATE INDEX ix_my_table_time_stamp ON my_table USING btree (time_stamp);

我还从查询中删除了“first”和“last”函数,以通知排序确实缺失。

有关如何按每15分钟步骤进行排序的建议吗?

1 个答案:

答案 0 :(得分:1)

没有标准的聚合函数containsfirst(),您可能意味着用户定义的聚合如:

last()

在aggegates中使用create or replace function first_agg(anyelement, anyelement) returns anyelement language sql immutable strict as $$ select $1; $$; create or replace function last_agg(anyelement, anyelement) returns anyelement language sql immutable strict as $$ select $2; $$; create aggregate first(anyelement) ( sfunc = first_agg, stype = anyelement ); create aggregate last(anyelement) ( sfunc = last_agg, stype = anyelement ); ,请参阅文档中的4.2.7. Aggregate Expressions

order by

DbFiddle.