日期:2014-05-18  浏览次数:20453 次

比较难SQL 语句
一个订单表有orderno,productid,price,flag,date,找出flag=0中,price大于flag=1中,目前productid的最新price的订单.也就是查出产品的价格大于已确认的最近的订单中的价格.真得很难讲清楚.简单的说就是一个订单中的产品价格不能比最近一次已入库的产品价格高.
问题的难点在于productid,在不同的单子中有同样的产品,怎样把这个产品找出来再用它来找出最近入库的价格.
帮帮吧

------解决方案--------------------

也就是说一个新进来的订单(这个单子里有多个产品),在验收时要验证每个产品(productid)的价格不能比最近入库的单子里产品的价格高.现在要把产品价格高的单子找出来.
表A orderno,productid,price,flag,date
select distinct orderno from A where flag=0 and price> (select top 1 price from A where productid=productid and flag=1 order by date desc)
现在的问题是如何处理productid,因为这个productid在同一个表里怎样区分要查的单子里的productid和原来已确认过的单子里的productid

第一个from A 改为 A as B 后面的 where 后面的句子改为 B.productid = A.productid
你再看看
------解决方案--------------------
select o.orderno, o.productid, o.price, o.date
from order o,
(select f0.productid, max(f0.price)
from (select orderno, productid, price, date
from order where flag = 0) f0,
(select orderno, productid, price, date
from order where flag = 1) f1
where f0.orderno = f1.orderno
and f0.productid = f1.productid
and f0.price > f1.price
group by f0.productid)
where tt o.productid = tt.productid
and o.price = tt.price;