最近公司要求使用达梦数据库,虽然很想念我的mysql和navicat,但是还是得硬着头皮上了。以下是结合项目需求产生的部分sql写法,或许有更优解,欢迎大佬们指出。
1. 按月、周、年分组查询数据总数
select count(*) as frequency,
to_char(O_TIME,'mm') as timeDimension
from EVENT
group by to_char(O_TIME,'mm')
select count(*) as frequency,
to_char(O_TIME,'iw') as timeDimension
from EVENT
group by to_char(O_TIME,'iw')
select count(*) as frequency,
to_char(O_TIME,'yyyy') as timeDimension
from EVENT
group by to_char(O_TIME,'yyyy')
2. 查询前7天数据,并且返回的时间格式为 月+日期(例:09-22)
SELECT TO_CHAR(O_TIME, 'MM-DD') AS timeDimension,
COUNT(*) AS frequency
FROM EVENT
WHERE O_TIME >= TO_DATE(TO_CHAR(SYSDATE - 7, 'yyyy-MM-dd hh24:mi:ss'), 'yyyy-MM-dd hh24:mi:ss')
GROUP BY TO_CHAR(O_TIME, 'MM-DD')
3. 查询一个月、半年、一年前的数据(合并为1条sql写法)
SELECT
E667.*
FROM EVENT E667
<where>
<if test="timeStampCode != null">
AND (#{timeStampCode} = 1 AND E667.O_TIME between add_months(now(),-1) and now())
OR
(#{timeStampCode} = 2 AND E667.O_TIME between add_months(now(),-1*6) and now())
OR
(#{timeStampCode} = 3 AND E667.O_TIME between add_months(now(),-1*12) and now())
</if>
</where>
order by E667.O_TIME desc