这个SQL怎么写?

zhzhxh 2009-01-20
比如有一个表,table1,里面存有一些商品的价格历史,比如说,有两个字段:goods_id, price。
我想找出价格变化量最大的前10个商品,这个能直接用SQL搞定吗?
大家想想看。
icefishc 2009-01-20
1. 可以
2. 什么叫变化最大
单次变化最大还是 总变化最大(初始价格 和现价格之间的差)
overyear 2009-01-21
是oracle?还mysql数据库?
都有专门的语法帮助你完成的。
zhzhxh 2009-01-21
icefishc 写道
1. 可以
2. 什么叫变化最大
单次变化最大还是 总变化最大(初始价格 和现价格之间的差)


可能是我没有说清楚

就比如,一个goods A,在这个表里有好几个价格,比如
goods_id | price | date
A | 12.00 | 01-12
A | 14.00 | 01-15
A | 16.00 | 01-20

变化量是最近的两次,也就是01-20和01-15两次的价格差(16.00-14.00=2.00)
zhzhxh 2009-01-21
overyear 写道
是oracle?还mysql数据库?
都有专门的语法帮助你完成的。


现在用的是Mysql,但是如果您知道怎么写,把两个都列出来吧,大家正好一块学习一下。谢谢
icefishc 2009-01-22
set @num1 := 0;
set @num2 := 0;
select gt1.goods_id, abs(gt1.price - gt2.price) difference
  from (select goods_id, price ,@num1 := @num1 + 1 as num 
          from goods  
          order by goods_id, date) gt1, 
       (select goods_id, price ,@num2 := @num2 + 1 as num 
          from goods  
          order by goods_id, date) gt2
  where gt1.goods_id = gt2.goods_id
    and gt1.num = gt2.num + 1
  order by difference desc
  limit 0, 10;
set @num1 := 0;
set @num2 := 0;


基本的想法就是给原表按照goods_id和data进行排序然后加上行号。
行号可以通过derived table 或临时表或其他什么东西来做
这样所谓上一次的值就是上一行的值而上一行在临时表中又可以通过行号得到
剩下的不用说了吧
希望我说清楚了。。。。。
祝你好运
zhzhxh 2009-01-24
icefishc 写道
set @num1 := 0;
set @num2 := 0;
select gt1.goods_id, abs(gt1.price - gt2.price) difference
  from (select goods_id, price ,@num1 := @num1 + 1 as num 
          from goods  
          order by goods_id, date) gt1, 
       (select goods_id, price ,@num2 := @num2 + 1 as num 
          from goods  
          order by goods_id, date) gt2
  where gt1.goods_id = gt2.goods_id
    and gt1.num = gt2.num + 1
  order by difference desc
  limit 0, 10;
set @num1 := 0;
set @num2 := 0;


基本的想法就是给原表按照goods_id和data进行排序然后加上行号。
行号可以通过derived table 或临时表或其他什么东西来做
这样所谓上一次的值就是上一行的值而上一行在临时表中又可以通过行号得到
剩下的不用说了吧
希望我说清楚了。。。。。
祝你好运


这个是mysql的存储过程吗,怎么还用了变量呢?
javaxiaoliu 2009-01-24
select g.price,g.date,g.goods,g1.date,ifnull(g1.price,0) as price,g1.goods,(g.price-ifnull(g1.price,0)) as dif from goods g
  left join goods g1 on g1.goods = g.goods and (select gs.date from goods gs where gs.date < g.date order by gs.date desc limit 1) = g1.date
group by g.goods
order  by dif desc limit 10
icefishc 2009-02-02
不是存储过程也能用变量啊
我那个方法太笨了 不要看了  
anranran 2009-02-05
先求差值
select abs(A.price-b.price) as 差值 from goods a,goods B where A.goods_id = b.goods_id

排序
select goods_id,差值 from
(select b.goods_id,abs(A.price-b.price) as 差值 from goods a,goods B where A.goods_id = b.goods_id) order by 差值

取前10
select top 10 distict(goods_id) from
(select goods_id,差值 from
(select b.goods_id,abs(A.price-b.price) as 差值 from goods a,goods B where A.goods_id = b.goods_id) order by 差值)

效率不高



Global site tag (gtag.js) - Google Analytics