这个pl/sql语句如何改成循环啊
初用oracle,pl/sql语句如下:
select '2012-09-18' 日期,lyjzm,TO_CHAR(sum(jzll),'99999999999.9') 井排液量,TO_CHAR(sum(jzyl),'99999999999.9') 井排油量
from ys_dhb12 t where zm='利津联合站'
and
((rq=to_date('2012-09-17','yyyy-MM-dd') and cjsj in('10:00','12:00','14:00','16:00','18:00','20:00','22:00')) or (rq=to_date('2012-09-18','yyyy-MM-dd') and cjsj in('0:00','2:00','4:00','6:00','8:00')))
and (lyjzm='注采站' or exists(select 1 from YS_DHA14 where zm=t.lyjzm and zb='11')) group by lyjzm
这个是查询某一天的产量,我想改成循环查询当月每天的产量,请问如何改啊
------解决方案--------------------for i in startDate .. endDate LOOP
begin
select i 日期,lyjzm,TO_CHAR(sum(jzll),'99999999999.9') 井排液量,TO_CHAR(sum(jzyl),'99999999999.9') 井排油量
from ys_dhb12 t where zm='利津联合站'
and
((rq=to_date(i-1,'yyyy-MM-dd') and cjsj in('10:00','12:00','14:00','16:00','18:00','20:00','22:00')) or (rq=to_date(i,'yyyy-MM-dd') and cjsj in('0:00','2:00','4:00','6:00','8:00')))
and (lyjzm='注采站' or exists(select 1 from YS_DHA14 where zm=t.lyjzm and zb='11')) group by lyjzm
end;
------解决方案----------------------写成月份循环比较麻烦,你需要去判断是否闫年,判断月份才能得到确定的循环次数,考虑指定月份查询。
SELECT TO_CHAR(rq,'yyyy-mm-dd') --'2012-09-18' 日期,
lyjzm,
TO_CHAR(SUM(jzll),'99999999999.9') 井排液量,
TO_CHAR(SUM(jzyl),'99999999999.9') 井排油量
FROM ys_dhb12 t
WHERE zm ='利津联合站'
/*
AND ((rq =to_date('2012-09-17','yyyy-MM-dd')
AND cjsj IN('10:00','12:00','14:00','16:00','18:00','20:00','22:00'))
OR (rq =to_date('2012-09-18','yyyy-MM-dd')
AND cjsj IN('0:00','2:00','4:00','6:00','8:00')))
*/
AND to_date(rq
|| cjsj
|| ':00','yyyy-mm-dd hh24:mi:ss') BETWEEN to_date(rq
|| '10:00:00','yyyy-mm-dd hh24:mi:ss')
AND to_date((rq +1)
|| '08:00:00','yyyy-mm-dd hh24:mi:ss')--取值范围=当天10点至第二天8点
and mod(to_char(to_date(cjsj,'hh24:mi'),'hh'),2) = 0 --每两小时的整点
and to_char(rq,'yyyy-mm') = '2012-09'--指定月份
AND (lyjzm='注采站'
OR EXISTS
(SELECT 1 FROM YS_DHA14 WHERE zm=t.lyjzm AND zb='11'
))
GROUP BY lyjzm
order by rq --按日期排序
------解决方案--------------------用trunc(sysdate,'mm')得到本月的第一天,
用last_date(sysdate)得到本月的最后一天,
然后写个循环就好
------解决方案--------------------
SQL code
--按照你的sql表达的意思就是,当天的10:00以后-到第二天8点之前 每两个小时的总量算做一天的
--不用循环呀兄弟,找出分组规律就ok了哦
SELECT TO_CHAR(RQ + 14 / 24, 'YYYY-MM-DD') 日期,
--这个分组在rq的基础上加了14个小时,那么自然前一天的10:00之后的数据显示的就是下一天
LYJZM,
TO_CHAR(SUM(JZLL), '99999999999.9') 井排液量,
TO_CHAR(SUM(JZYL), '99999999999.9') 井排油量
FROM YS_DHB12 T
WHERE ZM = '利津联合站'
/*
AND ((RQ = TO_DATE('2012-09-17', 'yyyy-MM-dd') AND
CJSJ IN
('10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00')) OR
(RQ = TO_DATE('2012-09-18', 'yyyy-MM-dd') AND
CJSJ IN ('0:00', '2:00', '4:00', '6:00', '8:00')))
*/
--下面这个条件就是 一个月的数据 只取偶数小时的
AND RQ BETWEEN TO_DATE('2012-08-31 10:00:00', 'YYYY-MM-DD HH24:MI:SS') AND
TO_DATE('2012-10-01 08:00:00', 'YYYY-MM-DD HH24:MI:SS')
AND MOD(TO_NUMBER(TO_CHAR(RQ, 'HH24')), 2) = 0
AND (LYJZM = '注采站' OR EXISTS (SELECT 1
FROM YS_DHA14
WHERE ZM = T.LYJZM
AND ZB = '11'))
GROUP BY TO_CHAR(RQ + 14 / 24, 'YYYY-MM-DD'), LYJZM;