[英]How to get the latest 2 rows ( PostgreSQL )
我需要您的帮助来修改查询以完成要求。
根据GATHER_TIME,我想显示名称的值。 该查询每1分钟运行一次,并且应始终获得2行。 如果当时没有数据,则应获取Name的过去(前1分钟)数据。
在这里,具体要求是我不应该在Timestamp值(GATHER_TIME)中考虑秒值。
我试图进行如下查询。 它仅获取最新数据。
你能帮我吗?
select NAME,sum(VALUE)
FROM TestTable
WHERE substring(to_char(gather_time,'YYYY-MM-DD HH24:MI:SS'),1,16) IN ( SELECT MAX(substring(to_char(gather_time,'YYYY-MM-DD HH24:MI:SS'),1,16)) FROM TestTable )
GROUP BY NAME
NAME COL1 COL2 GATHER_TIME VALUE
------------------------------------------------
first prince PQ1 2015-12-29 13:10:33 11
first prince PQ2 2015-12-29 13:10:33 14
first prince PQ3 2015-12-29 13:10:33 18
first prince PQ4 2015-12-29 13:10:33 19
second prince TT1 2015-12-29 13:10:59 20
second prince TT2 2015-12-29 13:10:59 29
second prince TT3 2015-12-29 13:10:59 43
first prince PQ1 2015-12-29 13:11:37 71
first prince PQ2 2015-12-29 13:11:37 74
first prince PQ3 2015-12-29 13:11:37 78
first prince PQ4 2015-12-29 13:11:37 79
@ Query time: 2015-12-29 13:10:59
first 62
second 92
@ Query time: 2015-12-29 13:11:59
first 302
second 92
抱歉。 我应该放更详细的测试数据。 更新了它。
SELECT DISTINCT ON (name,col1,gather_time) name,col1,SUM(value)
FROM test_table
GROUP BY name,col1,gather_time
ORDER BY gather_time DESC
LIMIT 2;
-- DDL
CREATE TABLE test_table(
name TEXT,
col2 TEXT,
gather_time TIMESTAMP,
value INTEGER
);
--sample data
INSERT INTO test_table VALUES
('first','PQ1','2015-12-29 13:10:33'::TIMESTAMP, 11),
('first','PQ2','2015-12-29 13:10:33'::TIMESTAMP, 14),
('first','PQ3','2015-12-29 13:10:33'::TIMESTAMP, 18),
('first','PQ4','2015-12-29 13:10:33'::TIMESTAMP, 19),
('second','TT1','2015-12-29 13:10:59'::TIMESTAMP, 20),
('second','TT2','2015-12-29 13:10:59'::TIMESTAMP, 29),
('second','TT3','2015-12-29 13:10:59'::TIMESTAMP, 43),
('first','PQ1','2015-12-29 13:11:37'::TIMESTAMP, 71),
('first','PQ2','2015-12-29 13:11:37'::TIMESTAMP, 74),
('first','PQ3','2015-12-29 13:11:37'::TIMESTAMP, 78),
('first','PQ4','2015-12-29 13:11:37'::TIMESTAMP, 79);
--query to run every minute
SELECT name,SUM(value) FROM test_table
WHERE gather_time <= now()
GROUP BY name,gather_time
ORDER BY gather_time DESC
LIMIT 2;
或使用功能:
CREATE OR REPLACE FUNCTION get_2latest_agg_rows(qtime timestamp)
RETURNS TABLE (
order_name TEXT,
sum_value BIGINT
) AS $$
BEGIN
RETURN QUERY
SELECT name as order_name,SUM(value) as agg_result FROM test_table
WHERE gather_time <= qtime::TIMESTAMP
GROUP BY name,gather_time
ORDER BY gather_time DESC
LIMIT 2;
END;
$$ LANGUAGE plpgsql;
--sample run
SELECT * FROM get_2latest_agg_rows('2015-12-29 13:11:59'::TIMESTAMP);
如果您将按collect_time排序并使用限制2来获取最新的2行怎么办? 符合要求吗?
select NAME,sum(VALUE) FROM TestTable ORDER BY gather_time DESC LIMIT 2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.