PostgreSQL/Oracle/Mysql查询最近12个月写法

PostgreSQL中查询前12个月的数据,举例:

with seq as (select 1 as rownum union all select 2 as rownum union all select 3 as rownum union all select 4 as rownum union all select 5 as rownum union all select 6 as rownum union all select 7 as rownum union all select 8 as rownum union all select 9 as rownum union all select 10 as rownum union all select 11 as rownum union all select 12 as rownum) select cTime.stt_date AXIS,cTime.ABBREVAXIS "abbrevAXIS",ROUND(nvl(a.VALUE1,0)/10000,2) VALUE1,ROUND(nvl(a.VALUE2,0)/10000,2) VALUE2 from ( select to_char(now()::timestamp + (-(rownum-1) || ' months')::interval,'YYYY-MM') as stt_date,to_char(now()::timestamp + (-(rownum-1)|| ' months')::interval,'MM') as ABBREVAXIS from seq ) cTime

PostgreSQL/Oracle/Mysql查询最近12个月写法

 

 

PostgreSQL/Oracle/Mysql查询最近12个月写法

 

 

--oracle 未来12个月
SELECT TO_CHAR(ADD_MONTHS(ADD_MONTHS(SYSDATE, 0), ROWNUM - 1),
'YYYY-MM') AS YEARMONTH
FROM ALL_OBJECTS
WHERE ROWNUM <= 12;

--oracle 前12个月
SELECT TO_CHAR(ADD_MONTHS(SYSDATE, 1 - ROWNUM),
'YYYY-MM') AS YEARMONTH
FROM ALL_OBJECTS
WHERE ROWNUM <= 12;

--mysql 前12个月
SELECT DATE_FORMAT(
date_add(NOW(), interval 1-(@rownum :=@rownum + 1) MONTH),
'%Y-%m') AS YEARMONTH
FROM information_schema.tables t1,(SELECT @rownum := 0) t2
limit 12;

--mysql 未来12个月
SELECT DATE_FORMAT(
date_add(NOW(), interval (@rownum :=@rownum + 1) -1 MONTH),
'%Y-%m') AS YEARMONTH
FROM information_schema.tables t1,(SELECT @rownum := 0) t2
limit 12;

-- 在PostgreSQL中可以直接对时间进行加减运算:SELECT now()::timestamp + '1 year';、

 --当前时间加1年

SELECT now()::timestamp + '1 year';  

'SELECT create_time + '1 year' from table;  

 

--当前时间加一个月
SELECT now()::timestamp + '1 month';  

SELECT create_time + '1month' from table;

 
--加1年1月1天1时1分1秒
select now()::timestamp + '1 year 1 month 1 day 1 hour 1 min 1 sec';  

selectcreate_time + '1 year 1 month 1 day 1 hour 1 min 1 sec';   

 --把col字段转换成天 然后相加
SELECT now()::timestamp + (col || ' day')::interval FROM table     

上一篇:Oracle 查询前几条记录


下一篇:ORACLE百万及上亿测试数据表创建