我有一个带有2个参数的函数:@iEmployeeID
和@dDate
。
它的目的是找到给定参数的预算率。换句话说,它应该找到最大日期小于或等于@dDate
参数,并返回对应的速率。
预算费率为:
Start Rate ------- ----- 01-01-2008 600 01-01-2009 800 01-01-2010 700
DECLARE @result decimal(38,20)
SELECT @result = decRate
FROM BudgetRates BR
WHERE BR.iRefEmployeeID = @iEmployeeID
GROUP BY decRate
HAVING MAX(BR.dStart) <= @dDate
RETURN @result
06-06-2008
时,它正确返回600. 03-03-2009
时,它正确返回800 02-02-2010
时,它应返回700.该函数实际返回800。错误在哪里?
寻找虫子: 如果我调整数字,如果它有两个可供选择的值,它似乎选择最大的费率。答案 0 :(得分:4)
肯定你的代码根本不应该分组?
SELECT TOP 1 @result = decRate
FROM BudgetRates BR
WHERE BR.iRefEmployeeID = @iEmployeeID
AND BR.dStart <= @dDate
ORDER BY BR.dStart DESC
RETURN @result
答案 1 :(得分:1)
您应该使用TOP 1
选择前1来获取ORDER BY
DECLARE @result decimal(38,20)
SELECT TOP 1 @result = decRate
FROM BudgetRates BR
WHERE BR.iRefEmployeeID = @iEmployeeID
ORDER BY decRate DESC
RETURN @result
答案 2 :(得分:1)
好像你应该在这里使用排名功能。
DECLARE @result decimal(38,20)
SELECT @result = decRate
(
SELECT decRate, ROW_NUMBER() OVER (ORDER BY BR.dStart DESC) rownum
FROM BudgetRates BR
WHERE BR.iRefEmployeeID = @iEmployeeID
AND BR.dStart <= @dDate
) sub
WHERE rownum = 1
RETURN @result
答案 3 :(得分:0)
尝试这个伴侣:
select @result = decRate
from BudgetRates
inner join (
select max(BR.dStart) as MaxDate
from BudgetRates
where BR.dStart <= @dDate
and BR.iRefEmployeeID = @iEmployeeID
) temp on tmep.MaxDate = BudgetRates.dStart
and BudgetRates.iRefEmployeeID = @iEmployeeID