日期:2014-05-17  浏览次数:20431 次

求一SQL,给跪了

如上图,分别为A、B表

希望获取如下结果:


文字说明:
A表:价格规则表 (每种房型在某天的价格规则表)
B表:房价表     (每种房型每天的原始价格)

他们的房型Code都是一样。
现在需要按照房型以及他们的日期来计算销售价格。

A中的EffectiveDate对应B中的RoomDate。
可以看出:
B在20130913、20130914两天,用的是A中20130913的价格规则。
B在20130915那天,用的是A中20130915那天的价格规则。
B在20130916那天,用的是A中20130916那天的价格规则

如果某天价格规则没有设置,那么按照它前面的那个(那个规则)计算。

------解决方案--------------------
select B.PMSRoomTypeCode,B.PMSRoomTypeName,B.RoomDate,B.price
,PriceRule=(select top 1 PriceRule from A 
where A.PMSRoomTypeCode=B.PMSRoomTypeCode and A.EffectiveDate<=B.RoomDate order by A.EffectiveDate desc) 
,PayAmount=(select top 1 PayAmount from A 
where A.PMSRoomTypeCode=B.PMSRoomTypeCode and A.EffectiveDate<=B.RoomDate order by A.EffectiveDate desc)
,B.PriceRuleType 
from B

------解决方案--------------------
瞧标题,不用跪啊,提出问题就行了,这里的人很热心的,一样会给解答的
------解决方案--------------------
SELECT
b.*, t.PriceRule, t.PayAmount, t.PriceRuleType
FROM B表 b
OUTER APPLY
(
SELECT TOP(1) PriceRule, PayAmount, PriceRuleType
FROM A表 a
WHERE a.RoomTypeCode = b.PMSRoomTypeCode
AND a.EffectiveDate <= b.RoomDate
ORDER BY a.EffectiveDate DESC
) t

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

select b.PMSRoomTypeCode,b.PMSRoomTypeName,b.RoomDate,b.Price,
       a.PriceRule,a.PayAmount,a.PriceRuleType
 from B表 b
 cross apply
 (select top 1 * from A表 a
   where b.PMSRoomTypeCode=a.RoomTypeCode 
   and cast(b.RoomDate as date)>=cast(a.EffectiveDate as date)
   order by cast(a.EffectiveDate as date) desc) a