Assuming that there is a table t with the following columns: Code int, Name nvarchar(50).
I'd would like to query the table for the most matching row for a given Code c. The 'most matching' criteria (in order of importance):
The code is going to be in a stored procedure.
Could someone please suggest how to accomplish the above.
Thanks.
Sample data and expected results:
1, "Name1"
2, "Name2"
4, "Name4"
5, "Name5"
If c=2, result: 2,"Name2"
If c=3, result: 4,"Name4"
if c=6, result: 5,"Name5"
I'd order the rows by two criteria - the absolute distance from the target number and whether it's greater or lesser than it, and just pick the top row. Eg, assuming the target code is 4:
SELECT TOP 1 *
FROM t
ORDER BY ABS(code - 4) ASC, CASE WHEN code > 4 THEN 1 ELSE 0 END DESC
That is a top 1 query; you want the one best matching record. So select TOP 1
along the desired order in ORDER BY
.
select top 1 *
from mytable
order by
case when code = @code then 1
when code > @code then 2
else 3
end,
abs(code - @code);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.