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

简单优选SQL ???
Table1表,如何根据给出houdu厚度,kuandu宽度,changdu长度,进行优选选择材料
举例:houdu=0.7(厚度是先给出的是定值,一定先要根据给定houdu再根据给出的kuandu,changdu进行优选,优选后的宽度要大于等于给出kuandu,changdu也是,找出最接近的,单一定要比给出的大,如果没有匹配的查询结果为空),给出kuandu=830,changdu=1100,优选后最接近的材料为 木板2 0.7 850 1200,如给定kuandu=900,changdu=1050,则优选后就是 木板3 0.7 950 2000,如给定kuandu=1200,changdu=800,优选后结果为空 请问SQL如何优选 ?(以宽度优先,给出指定厚度,宽度后,如宽度没有符合的结果直接为空,如kuandu有符合找changdu最接近的)
求SQL  

name houdu kuandu changdu
木板1 0.7 850 1000
木板2 0.7 850 1200
木板3 0.7 950 2000
木板4 0.7 1100 750
木板5 0.7 600 1100

------解决方案--------------------
SQL code

--> 测试数据: @T
declare @T table (name varchar(5),houdu numeric(2,1),kuandu int,changdu int)
insert into @T
select '木板1',0.7,850,1000 union all
select '木板2',0.7,850,1200 union all
select '木板3',0.7,950,2000 union all
select '木板4',0.7,1100,750 union all
select '木板5',0.7,600,1100

--变量自行设定
declare @houdu numeric(2,1) set @houdu=0.7
declare @kuandu int set @kuandu=900 
declare @changdu int set @changdu=1050
--查询
select top 1 * from @T
where  houdu>=@houdu and kuandu>=@kuandu and changdu>=@changdu
order by houdu,kuandu,changdu
--结果
/*
name  houdu                                   kuandu      changdu
----- --------------------------------------- ----------- -----------
木板3   0.7                                     950         2000
*/

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

[/code]
--> 测试数据:tbl
go
if object_id('tbl') is not null 
drop table [tbl]
go
create table [tbl](
name varchar(5),
houdu numeric(2,1),
kuandu int,
changdu int
)
insert tbl
select '木板1',0.7,850,1000 union all
select '木板2',0.7,850,1200 union all
select '木板3',0.7,950,2000 union all
select '木板4',0.7,1100,750 union all
select '木板5',0.7,600,1100 union all
select '木板1',0.6,850,1000 union all
select '木板2',0.6,850,1200 union all
select '木板3',0.6,950,2000 union all
select '木板4',0.6,1100,750

declare @houdu numeric(2,1)
set @houdu=0.7
declare @kuandu int
declare @changdu int
select @kuandu=830,@changdu=1100
create table #t(
id int identity(1,1),
name varchar(5),
houdu numeric(2,1),
kuandu int,
changdu int,
kuanducha int,
changducha int
)
insert #t
select name,houdu,kuandu,
changdu,kuandu-@kuandu,changdu-@changdu from tbl
where houdu=@houdu and kuandu>@kuandu
and changdu>@changdu 
order by kuandu-@kuandu,changdu-@changdu asc

select top 1 name,houdu,kuandu,changdu from #t 


name houdu kuandu changdu
木板2 0.7 850 1200
[/code]