本董想实现如下的语句:SELECT 时间,开盘价,最高价,最低价,收盘价,FUN1(5) as 前五天最高价中的最大值,FUN2(2) as 前两天的开盘价,FUC3(1) as 往后一天的收盘价 FORM 美元兑日元数据表FUN1(N):取从当前"时间"记录起前N条记录中的"最高价"中的最大数;
FUN2(N):取从当前"时间"记录起前N条记录中的"开盘价";
FUN3(N):取从当前"时间"记录起后N条记录中的"收盘价".请帮我实现以上函数,并给出完整的SELECT及函数,分不够的请到水园回复“zyq_123”或“Yongsoft123”所发的未结贴,回复时注明“已经帮我解决了SQL的问题”。

解决方案 »

  1.   

    --由于在2000的用户自定义函数里边有许多限制,如不能使用sp_executesql,set rowcount等,所以在2000里边使用用户自定义函数不太好实现你的需求.可以使用子查询来实现.手动的改变top 后边的参数就可以实现你的需求了.select *,
           (select max(最高价) from (select top 5 最高价  --  前五条记录的最高价
                                     from 美元兑日元数据表
                                     where 时间<a.时间
                                     order by 时间 desc) t) as Max_Price,
           (select top 1 开盘价 from (select top 2 开盘价,时间
                                    from 美元兑日元数据表  --  前两条记录的开盘价
                                    where 时间<a.时间
                                    order by 时间 desc) t
            order by 时间) as Open_Price,           -- 后一条记录的收盘价
           (select top 1 收盘价 from (select top 3 收盘价,时间
                                       from 美元兑日元数据表
                                       where 时间>a.时间
                                       order by 时间) t
            order by 时间) as Close_Price
    from 美元兑日元数据表 a
      

  2.   

    --如果你的表非常大的话,回有性能上的问题.最好在时间上建立聚集索引.create clustered index idx_cl_Price on 美元兑日元数据表(时间)
      

  3.   

    --在SQL SERVER 2005里边可以很好的解决你这个问题.因为SQL SERVER 2005允许在Top后边使用变量了.--  前N最高价格
    create function dbo.fn_MaxPrice
    (@v_N int,
     @v_trade_date Datetime)
    returns money
    as
    begin
    declare @v_MaxPrice moneyselect @v_MaxPrice=max(最高价)
    from(select top (@v_N) 最高价 from 美元兑日元数据表
     where 时间<@v_trade_date
     order by 时间 desc) treturn @v_MaxPrice
    end
    Go--  前N开盘价格create function dbo.fn_OpenPrice
    (@v_N int,
     @v_trade_date datetime)
    returns money
    as
    begin
    declare @v_OpenPrice moneyselect top 1 @v_OpenPrice=开盘价
    from
    (
    select top (@v_N) 开盘价,日期
    from 美元兑日元数据表
    where 日期<@v_trade_date
    order by 日期 desc
    ) t order by 日期return @v_OpenPrice
    end
    Go--  后N条记录的收盘价格create function dbo.fn_ClosePrice
    (@v_N int,
     @v_trade_date datetime)
    returns money
    as
    begin
    declare @v_ClosePrice moneyselect top 1 @v_ClosePrice=收盘价
    from 
    (
    select top (@v_N) 收盘价,时间
    from 美元兑日元数据表
    where 日期>@v_trade_date
    order by 日期
    ) t order by 日期 desc return @v_ClosePrice
    end
    Go--  执行查询
    select dbo.fn_MaxPrice(5,时间) as Max_Price,
           dbo.fn_OpenPrice(2,时间) as Open_Price,
           dbo.fn_ClosePrice(1,时间) as Close_Price,
    *
    from 美元兑日元数据表
    order by 时间
      

  4.   

    要求必须是SQL SERVER2000下的函数,不给出函数的一分也不给。
      

  5.   

    mschen(Co-ok)老弟,你自己测试过没有?
      

  6.   

    呵呵,CO-OK做的是脚本,不是函数,你还要自己改一下.