有一个表PriceRecord,结构是这样的:
cCode varchar(10)
dDate DateTime
iPrice floatSelect * from priceRecord Order by cCode,dDate,iPrice我取另一个表(表A)的记录与此表关联,关联字段是cCode,现在的问题是关联后我要以表A的日期字段为参照,取PriceRecord表的比表A.dDate早的最近日期的价格记录,如果比表A日期早的记录不存在,则取比表A日期晚的最近日期的价格记录,如何处理(用一句SQL解决),请大侠指导?
cCode varchar(10)
dDate DateTime
iPrice floatSelect * from priceRecord Order by cCode,dDate,iPrice我取另一个表(表A)的记录与此表关联,关联字段是cCode,现在的问题是关联后我要以表A的日期字段为参照,取PriceRecord表的比表A.dDate早的最近日期的价格记录,如果比表A日期早的记录不存在,则取比表A日期晚的最近日期的价格记录,如何处理(用一句SQL解决),请大侠指导?
给定一个日期常量,比如说“2006-01-01”
要求从PriceRecord表中取日期(dDate)早于“2006-01-01”但离“2006-01-01”
最近的iPrice的值,如果早于“2006-01-01”日期的记录不存在,则取日期(dDate)晚于“2006-01-01”但离“2006-01-01”最近的iPrice的值或者取等于“2006-01-01”的iPrice的值。
FROM PriceCode
INNER JOIN A ON PriceCode.cCode=A.Code AND PriceCode.dDate>=A.dDate如果不正确就把两个表中的数据贴出来再说规则更直观.
select a.*
from a inner join pricecode b on b.ccode = a.code
where b.ddate = (select max(c.ddate)
from pricecode c
where c.ccode = b.ccode and c.ddate < a.ddate)
给定一个日期常量,比如说“2006-01-01”
要求从PriceRecord表中取日期(dDate)早于“2006-01-01”但离“2006-01-01”
最近的iPrice的值,如果早于“2006-01-01”日期的记录不存在,则取日期(dDate)晚于“2006-01-01”但离“2006-01-01”最近的iPrice的值或者取等于“2006-01-01”的iPrice的值。(SQL语句解决)
数据如下:0001 2003-04-16 00:00:00.000 3.0
0001 2006-04-04 00:00:00.000 3.5
0002 2003-04-11 00:00:00.000 9.0
0002 2003-04-11 00:00:00.000 10.0
0004 2003-04-04 00:00:00.000 6.5999999999999996
0004 2003-04-16 00:00:00.000 6.7000000000000002
0004 2006-04-16 00:00:00.000 6.7000000000000002
1003 2006-03-08 00:00:00.000 343.0
加入当前日期为: 2006-01-01,则通过SQL语句查询出以下结果:
0001 2003-04-16 00:00:00.000 3.0
0002 2003-04-11 00:00:00.000 9.0
0004 2003-04-16 00:00:00.000 6.7000000000000002
1003 2006-03-08 00:00:00.000 343.0当然,获得这样的SQL以后我可以通过关联把“2006-01-01”改为表A的日期字段。
然后:AdoQuery1.last,指向最后一条记录这样一来可以么?
我看到比2006-01-01早的最近的日期都是对的了。
再加上如果这些记录不存在,则取比2006-01-01晚的最近的记录或者取等于2006-01-01的
记录就全对了。
select a.*
from a inner join pricecode b on b.ccode = a.code
where b.ddate = case when exists
(select d.ddate from pricecode d where d.ccode=b.ccode and d.ddate < a.ddate) then
(select max(c.ddate) from pricecode c where c.ccode = b.ccode and c.ddate < a.ddate)
else
(select min(c.ddate)from pricecode c where c.ccode = b.ccode and c.ddate > a.ddate)
end
Select distinct b.*
from avgprice b
where b.ddate = case when exists
(select c.ddate From avgprice c where c.cInvcode = b.cInvcode and c.ddate < '2006-01-01') then
(select max(d.ddate) From avgprice d where d.cInvcode = b.cInvcode and d.ddate < '2006-01-01')
else
(select min(d.ddate) From avgprice d where d.cInvcode = b.cInvcode and d.ddate >= '2006-01-01')
endmerkey2002(小样的) 大虾超牛。
谢谢。