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

[求助]一个自定义函数的算法
目标表:tbl_a

主要字段:type   (int)   --类型
          price   (decimal)       --价格

数据样式:
type           price
--------------------------------------------
1                 5000
2                 5150
3                 5200
4                 5300
5                 5450
6                 5650
7                 5750
8                 5900
...
现在要写一个函数,根据给出的任意一个price值,比如5500,求得最接近这个5500(大于或等于)的type值和price值.
比如:5500   ,得到的应该是price=5650,type=6,而不是5450.

这样的函数应该怎么写啊,请高手指点.
谢谢!


------解决方案--------------------
select top 1 type, price
from 表名
where price> =5500
order by price

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


select top 1 * from tbl_a
where (price-5550)> =0

--result
6 5650

------解决方案--------------------
这不简单吗

select top 1 type, price
from tbl_a
where price> =5500
order by price
------解决方案--------------------
create table test(type int,price int)
insert test select 1,5000
union all select 2,5150
union all select 3,5200
union all select 4,5300
union all select 5,5450
union all select 6,5650
union all select 7,5750
union all select 8,5900
go

create function fun(@price int)
returns int
as
begin
declare @i int
set @i=0
select @i=min(price) from
(
select price,type from test where price> =@price
)a
return @i
end
go

select type,price from test where price=dbo.fun(5500)

drop table test
drop function fun

type price
----------- -----------
6 5650
------解决方案--------------------
create table tbl_a(type int,price decimal)
insert tbl_a select
1, 5000 insert tbl_a select
2, 5150 insert tbl_a select
3, 5200 insert tbl_a select
4, 5300 insert tbl_a select
5, 5450 insert tbl_a select
6, 5650 insert tbl_a select
7, 5750 insert tbl_a select
8, 5900
-----------------------
create alter function fun_a(@a decimal)returns table
return (select top 1 type,price from tbl_a where price> =@a order by price-@a )
------------------------
select * from fun_a(5500)