获取两个日期之间的最大日期/时间

时间:2016-11-19 21:22:19

标签: sql postgresql date datetime

我想查询两个日期/时间之间的几个字段的表,我需要确定两个日期/时间之间的最大日期和时间。

该表包含以下类型的字段: validtime | datavalue | basistime | PE1 | PE2 | T | S |盖

有效时间是对数据值有效的日期/时间,而基准时间是创建数据值的日期/时间。我需要找到两个日期/时间之间的最大值(基准时间)。

这就是我现在所拥有的,但没有成功:

SELECT validtime, datavalue, max(basistime) from ped where lid='XXXXX' and
and pe1='H' and pe2='G' and t='C' and s='Z' and basistime>='2014-11-19 
12:00:00' and basistime<'2014-11-19 23:45:00' group by ped.validtime,        
ped.datavalue, ped.basistime;

我也尝试了以下内容:

SELECT validtime, datavalue, (SELECT MAX(basistime) from ped where
lid='XXXXX' and pe1='H' and pe2='G' and t='C' and s='Z' and 
basistime>='2014-11-19 12:00:00' and basistime<'2014-11-19 23:45:00')
from ped where lid='XXXXX' and pe1='H' and pe2='G' and t='C' and s='Z'
and basistime>='2014-11-19 12:00:00' and basistime<'2014-11-19 23:45:00'; 

CREATE TEMPORARY TABLE temp AS SELECT basistime, validtime, datavalue, lid, 
pe1, pe2, t, s, from ped where lid='XXXXX' and pe1='H' and pe2='G' and t='C'
and s='Z' and basistime>='2014-11-19 12:00:00' and basistime<'2014-11-19
23:45:00' group by ped.validtime, ped.datavalue; SELECT t.validtime,
t.datavalue from temp t where t.lid='XXXXX' and t.basistime=max(t.basistime) 
order by validtime ASC;

CREATE TEMPORARY TABLE temp AS SELECT max(basistime), validtime, datavalue,      
lid, pe1, pe2, t, s, from ped where lid='XXXXX' and pe1='H' and pe2='G' and 
t='C' and s='Z' and basistime>='2014-11-19 12:00:00' and basistime<'2014-11-     
19 23:45:00'; SELECT t.validtime, t.datavalue from temp t where     
t.lid='XXXXX' and t.basistime=max(t.basistime) order by validtime ASC;

我还尝试将基准时间作为文本投射,并在2个日期使用BETWEEN。

上述大多数查询都不会产生任何数据。我发布的第一个产生数据,但日期是从2009年开始的(显然不在我提供的两个日期之间)。

将输出所需的结果,例如: validtime,datavalue,max(basistime)

我已经阅读了我在stackoverflow上可以找到的每个条目,否则,但我还没有找到解决方案。非常感谢您的帮助。

2 个答案:

答案 0 :(得分:3)

如果您想要max(基准时间),则不必将此列添加到

分组
SELECT validtime, datavalue, max(basistime) 
from ped 
where lid='XXXXX' 
and pe1='H'
and pe2='G' 
and t='C' 
and s='Z' 
and basistime>='2014-11-19 12:00:00' 
and basistime<'2014-11-19 23:45:00' 
group by validtime,  datavalue

答案 1 :(得分:-1)

非常感谢大家。事实证明这是两个相对简单的事情的组合。正如scaisEdge所提到的,我需要按部分添加基准时间,我也缺少一些括号。这是最终版本:

SELECT validtime, datavalue, max(basistime) from ped 
where lid='XXXXX' and pe1='H' and pe2='G' and t='C' and s='Z' 
and (basistime>='2014-11-19 12:00:00' and basistime<'2014-11-19 23:45:00') 
group by validtime,datavalue,basistime
order by validtime;