大家看看这样的查询怎么实现 查询出全部商品在某一时间段内的最近一次订货的时间以及订货数量 字段有:商品ID,订货时间,订货数量(订货时间来自于主表,其余的来自于从表)结果返回:商品ID,最近订货时间,最近订货数量 。 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 我来试试:SELECT B.ID,B.MAX_TIME,A.NUM FROM T A,(SELECT ID,MAX(TIME) MAX_TIME FROM T GROUP BY ID) BWHERE A.ID=B.ID AND A.TIME=B.MAX_TIME; 外面还要再套一个GROUP BY ID,因为可能会存在一种商品同一天订购好几笔的情况。不过这样的语句执行起来效率是好差的。 select * from (select rank() over(partition by 商品ID order by 订货时间 desc) rk,a.* from a) t where t.rk<=1; SQL> create table 主表( 2 商品ID number, 3 订货时间 date 4 );Table createdSQL> create table 从表( 2 商品ID number, 3 订货数量 number 4 );Table createdSQL> insert into 主表 2 select 1, sysdate-1 from dual union 3 select 2, sysdate-2 from dual union 4 select 1, sysdate from dual union 5 select 2, sysdate from dual;4 rows insertedSQL> commit;Commit completeSQL> insert into 从表 2 select 1, 100 from dual union 3 select 2, 200 from dual;2 rows insertedSQL> commit;Commit completeSQL> select * 2 from 主表; 商品ID 订货时间---------- ----------- 1 2006-1-6 16 1 2006-1-7 16 2 2006-1-5 16 2 2006-1-7 16SQL> select * 2 from 从表; 商品ID 订货数量---------- ---------- 1 100 2 200SQL> select a.商品ID, b.订货时间, a.订货数量 2 from 从表 a, ( select row_number() over ( partition by 商品ID order by 订货时间 desc ) num, 订货时间, 商品ID 3 from 主表 4 ) b 5 where a.商品ID = b.商品ID 6 and b.num = 1; 商品ID 订货时间 订货数量---------- ----------- ---------- 1 2006-1-7 16 100 2 2006-1-7 16 200SQL> 这个不错,执行效率有大幅度的提高,我用的是ORACLE,SQL SERVER中是不是也有此函数? to hncdsun(魔):订货时间和订货数量当然要分开了,因为这里的订货数量指的是每一种商品的订货数量,而一个订单中要有好多个商品的. 我试过了,RANK()不支持ORACLE 8XX 以下的版本。 不错,用分析函数!!Oracle817是可以的 Oracle安装问题 怎样使用Proc.exe预编译PC源程序 oracle返回数据问题。在线等。 求助group by a having count()问题 请大家看看这个表在设计上有什么问题 如何让oracle多条记录的同一列的值随机组合,然后再把对应的值也组合显示出来,急啊,求大神帮助。。。。 Help!如何将一个Base64字串还愿? 一段SQL独立在SQL/PLUS中可以运行,写在过程里面就不对了? ===求存储过程,关于事务处理=== oracle816 oem的导航器中怎么只有组,节点和developer servers 一个很简单的存储过程,兄弟们帮看一下哪错了? 很简单
SELECT B.ID,B.MAX_TIME,A.NUM
FROM T A,(SELECT ID,MAX(TIME) MAX_TIME FROM T GROUP BY ID) B
WHERE A.ID=B.ID AND A.TIME=B.MAX_TIME;
不过这样的语句执行起来效率是好差的。
2 商品ID number,
3 订货时间 date
4 );Table createdSQL> create table 从表(
2 商品ID number,
3 订货数量 number
4 );Table createdSQL> insert into 主表
2 select 1, sysdate-1 from dual union
3 select 2, sysdate-2 from dual union
4 select 1, sysdate from dual union
5 select 2, sysdate from dual;4 rows insertedSQL> commit;Commit completeSQL> insert into 从表
2 select 1, 100 from dual union
3 select 2, 200 from dual;2 rows insertedSQL> commit;Commit completeSQL> select *
2 from 主表; 商品ID 订货时间
---------- -----------
1 2006-1-6 16
1 2006-1-7 16
2 2006-1-5 16
2 2006-1-7 16SQL> select *
2 from 从表; 商品ID 订货数量
---------- ----------
1 100
2 200SQL> select a.商品ID, b.订货时间, a.订货数量
2 from 从表 a, ( select row_number() over ( partition by 商品ID order by 订货时间 desc ) num, 订货时间, 商品ID
3 from 主表
4 ) b
5 where a.商品ID = b.商品ID
6 and b.num = 1; 商品ID 订货时间 订货数量
---------- ----------- ----------
1 2006-1-7 16 100
2 2006-1-7 16 200SQL>
订货时间和订货数量当然要分开了,因为这里的订货数量指的是每一种商品的订货数量,而一个订单中要有好多个商品的.