遇到同步數據類工作通常需要對日期進行轉換,記錄一下Informix SQL遇到的寫法。
標准sql語法和Informix SQL 函數可百度了解.
1、准備測試表
由於Informix沒有dual表,我們新建test_tab,並插入一條數據作為測試表。
- 建表
--建表
create table test_tab(
testId int,
insert_time datetime year to second default current year to second --插入時間 默認當前時間
);
--插入一條數據
insert into test_tab(testId) values(1);
- 查看測試表
--查詢測試表
select * from test_tab;
testId | insert_time |
---|---|
1 | 2018-11-28 16:31:18 |
2、日期轉換
- 轉換日期為指定字符串格式,如yyyy-MM-dd HH:mm:ss格式:
select testid, to_char(today, '%Y-%m-%d %H:%M:%S') as cur_time
from test_tab;
testId | cur_time |
---|---|
1 | 2018-11-28 00:00:00 |
today 指今天 yyyy-MM-dd
- 轉換字符串為日期格式,如字符串 '2018/11/28 16:31:18'
select testid, to_date('2018/11/28 16:31:18', '%Y/%m/%d %H:%M:%S') as cur_time
from test_tab;
testId | cur_time |
---|---|
1 | 2018-11-28 16:31:18 |
3、獲取上個小時,昨天和上個月
理解了相關函數,實現方式非常多,接下來會舉一些例子。
- 昨天
select testid, today - 1 as yeaterday
,sysdate - 1 units day as yeaterday_t
from test_tab;
testId | yeaterday | yeaterday_t |
---|---|---|
1 | 2018-11-27 | 2018-11-27 16:31:18 |
sysdate 指當前時間 yyyy-MM-dd HH:mm:ss
當前時間減去一天即為昨天此時
- 上個小時
select testid
,sysdate-1 units hour lasthour
,sysdate - interval(1) hour to hour lasthour1
,extend(sysdate-1 units hour,year to hour) lasthour2
from test_tab;
testId | lasthour | lasthour1 | lasthour2 |
---|---|---|---|
1 | 2018-11-28 16:29:03 | 2018-11-28 16:29:03 | 2018-11-28 16:00:00 |
extend 可以把日期處理成想要的精度
- 上周日期
select testid,today as cur_date
,to_char(today,'%A') as weekstr
,weekday(today) as wday
,today -weekday(today) as lastsunday
,today -weekday(today)-6 as lastmonday
from test_tab;
testId | cur_date | weekstr | wday | lastsunday | lastmonday |
---|---|---|---|---|---|
1 | 2018-11-28 | Wednesday | 3 | 2018-11-25 | 2018-11-19 |
weekday(today) 顯示當前是周的第幾天,可以理解為 dayOfWeek
day(today)則可表示dayOfMonth
- 上月日期
select testid,today as cur_date
,to_char(sysdate-1 units month,'%Y%m') as lastmon_str
,day(today) as dday
,today -day(today) as lastmon_end
,to_date(to_char(sysdate-1 units month,'%Y%m')|| '01', '%Y%m%d') as lastmon_begin
,extend(sysdate - 1 units month,year to month) as lastmon_begin1
from test_tab;
testId | cur_date | lastmon_str | dday | lastmon_end | lastmon_begin | lastmon_begin1 |
---|---|---|---|---|---|---|
1 | 2018-11-28 | 201810 | 28 | 2018-10-31 | 2018-10-01 00:00:00 | 2018-10-01 00:00:00 |
select testid,today as cur_date
,mdy(month(today),1,year(today)) thismonth
,mdy(month(today)-1,1,year(today)) lastmon_begin
,mdy(month(today),1,year(today))-1 units day lastmon_end
from test_tab
testId | cur_date | thismonth | lastmon_begin | lastmon_end |
---|---|---|---|---|
1 | 2018-11-28 | 2018-11-01 | 2018-10-01 | 2018-10-31 00:00:00 |
informix里字符串拼接使用 "||"
mdy(m,d,y)