PostgreSQL,从文本列获取最小和最大日期 [英] PostgreSQL, getting min and max date from text column

查看:1318
本文介绍了PostgreSQL,从文本列获取最小和最大日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表中有这样的情况:

I have such situation in table:

1   01.02.2011
2   05.01.2011
3   06.03.2012
4   07.08.2011
5   04.03.2013
6   06.08.2011
7   
8   02.02.2013
9   04.06.2010
10  10.10.2012
11  04.04.2012

其中第一列是id( INT),第二列是TEXT,其中的日期可以写为 dd.mm.yyyy格式。

where first column is id (INT) and second column is TEXT in which may be written date in format 'dd.mm.yyyy'.

我想获得:

1)整个表中的最低输入日期,而整个表中的最高输入日期。

2)2012年的最低输入日期,2012年的最高输入日期。

I would like to get:
1) lowest entered date in whole table and highest entered date in whole table.
2) lowest entered date in year 2012 and highest entered date in year 2012.

年份中的最低日期和最高日期可能相同(例如2010年),或者字段可能为空(例如第7行)。

Lowest and highest date in year may be a same (like for year 2010) or field may be empty (like in row 7).

我是试图使用TO_TIMESTAMP,但未成功。
示例:

I am tying to use TO_TIMESTAMP but unsuccessfully. Example:

SELECT (TO_TIMESTAMP(mydatetxt, 'DD.MM.YYYY'))   
FROM " & myTable & "   
ORDER BY (TO_TIMESTAMP(mydatetxt, 'DD.MM.YYYY')) ASC LIMIT 1  

还有BETWEEN,我也不会得到想要的结果。

Also with BETWEEN I don't get wanted result.

如何编写这两个查询?

解决方案:

感谢您的所有建议。

Igor的解决方案对我来说最合适,也很简单。

SOLUTION:
Thanks for all suggestions.
Igor's solution is most suitable and simple enough for me.

Dim sqlText As String = "SELECT min(to_date(nullif(mydate,''), 'DD.MM.YYYY')) FROM " & mytable
cmd1 = New NpgsqlCommand(sqlText, conn)
min = CDate(cmd1.ExecuteScalar())
If Not IsDate(min) Then
    min = CType(CDate("01.01." & myyear) & " 00:00:00", Date)
End If
fromdate = CType(CDate(min), Date)

sqlText = "SELECT max(to_date(mydate, 'DD.MM.YYYY')) FROM " & mytable
cmd1 = New NpgsqlCommand(sqlText, conn)
max = CDate(cmd1.ExecuteScalar())
If Not IsDate(max) Then
    max = CType(CDate("31.12." & myyear) & " 23:59:59.9999", Date)
End If
todate = CType(CDate(max), Date)


推荐答案

尝试类似的操作:

SELECT max(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY')),
       min(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY'))
FROM table_name;

SELECT max(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY')),
       min(to_date(nullif(mydatetxt,''), 'DD.MM.YYYY'))
FROM table_name
WHERE date_part('year',to_date(nullif(mydatetxt,''), 'DD.MM.YYYY')) = 2012;

这篇关于PostgreSQL,从文本列获取最小和最大日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆