一张表tableAid field1 field2 price date1 date2
1 3 4 200 2007.01.01 2007.01.31
2 3 4 180 2007.02.01 2007.02.28
3 3 4 270 2007.03.01 2007.03.15
4 2 2 250 2007.01.01 2007.02.28
5 1 2 300 2007.01.01 2007.01.30
...我要查出范围在 2007.01.29 - 2007.02.02 之间的每天的price的所有结果, 相同的field1和field2才是同一个项目的,结果应该是:field1 field2 price price price price price
3 4 200 200 200 180 180
2 2 250 250 250 250 250
如何写这个查询语句?
可能写一个语句有点复杂,不能完成,是否必须存储过程才能完成?
1 3 4 200 2007.01.01 2007.01.31
2 3 4 180 2007.02.01 2007.02.28
3 3 4 270 2007.03.01 2007.03.15
4 2 2 250 2007.01.01 2007.02.28
5 1 2 300 2007.01.01 2007.01.30
...我要查出范围在 2007.01.29 - 2007.02.02 之间的每天的price的所有结果, 相同的field1和field2才是同一个项目的,结果应该是:field1 field2 price price price price price
3 4 200 200 200 180 180
2 2 250 250 250 250 250
如何写这个查询语句?
可能写一个语句有点复杂,不能完成,是否必须存储过程才能完成?
解决方案 »
- 如何定时清理历史数据。
- 写了个过程 老是提示错误
- 错误 ORA-08103: object no longer exists , 有一个表 返回10条数据没问题,但是返回1000条 数据 就报这个错误
- 怎样写sql删除最新的几条数据
- 简单的sql语句帮忙看看
- 安装oracle之后,找不到tg4msql这个目录,是因为少安装了哪个项目?
- 存储过程中的sql语句问题
- 求助ora-01033 的问题
- 请问Database,Schema,Catalog三者之间的区别
- oracle查询语句出错 ORA-00904: "A"."COMP_ID": 标识符无效
- 查询两字段同时不满足的记录
- 关于访问oracle数据库数据是乱码的问题
create table tablea
(id int, field1 int,field2 int,price int,date1 date,date2 date)
id field1 field2 price date1 date2
insert into tablea
select 1,3,4,200,to_date('2007.01.01','yyyy-mm-dd'),to_date('2007.01.31','yyyy-mm-dd') from dual union all
select 2,3,4,180,to_date('2007.02.01','yyyy-mm-dd'),to_date('2007.02.28','yyyy-mm-dd') from dual union all
select 3,3,4,270,to_date('2007.03.01','yyyy-mm-dd'),to_date('2007.03.15','yyyy-mm-dd') from dual union all
select 4,2,2,250,to_date('2007.01.01','yyyy-mm-dd'),to_date('2007.02.28','yyyy-mm-dd') from dual union all
select 5,1,2,300,to_date('2007.01.01','yyyy-mm-dd'),to_date('2007.01.30','yyyy-mm-dd') from dual;
--存储过程
create or replace procedure (sdate in varchar2(20),eDate in varchar2(20),rst out sys_refcursor )
is
days int;
IntI int;
fdate varchar2(20);
sqlStr varchar2(4000);
begin
sqlStr:='select t.field1,t.field2,';
select to_date(sdate,'yyyy-mm-dd') - to_date(eDate,'yyyy.mm.dd') into days from dual;
for IntI in 0..days loop
fdate:=to_char(to_date(sdate,'yyyy-mm-dd')+IntI,'yyyy-mm-dd');
sqlStr:=sqlStr||'(select price from tablea where field1=t.field1 and field2=t.field2 and (to_date('''||fdate||''',''yyyy-mm-dd'')>=date1 and to_date('''||fdate||''',''yyyy-mm-dd'')<=date2 )) price'||IntI||', ';
end loop;
sqlStr:=substr( sqlstr,1,length( sqlstr )-2);
sqlStr:=sqlStr||' from (select field1,field2, min(date1) date1,max(date2) date2 from tablea group by field1,field2) t where date1<=to_date('||sdate||',''yyyy.mm.dd'') and date2>=to_date('||edate||',''yyyy-mm-dd'') ';
insert into ttt values( sqlstr );
open rst for sqlstr;
end;--测试结果
2 2 250 250 250 250 250
3 4 200 200 200 180 180
sqlStr:=substr( sqlstr,1,length( sqlstr )-2); 应该是
sqlStr:=substr( sqlstr,1,length( sqlstr )-1); 吧?
而且输出里没有价格
3 4 200 200 200 180 180
2 2 250 250 250 250 250
可是第一行的field1与field2并不相同呀?