我正在寻找一种方法来获取排列或排序的表中的所有记录,使得匹配的最大列数位于顶部,然后进一步
示例:表名称(车辆)
Id Name VehicleMileage VehicleAverage VehicleCC Gear
1 Vehicle1 30HP@2000 25000 1000 3
2 Vehicle2 30HP@2000 22000 8000 2
3 Vehicle3 20HP@2000 21000 5000 4
4 Vehicle4 60HP@2000 25000 1000 3
5 Vehicle5 70HP@2000 23000 3000 3
这里假设搜索到的参数如下:
VehicleMileage: 30HP@2000
VehicleAverage: 25000
VehicleCC: 1000
Gear: 3
查询结果将遵循以下顺序:
Vehicle1 (Reason: 4 matched columns)
Vehicle4 (Reason: 3 matched columns)
Vehicle2 (Reason: 1 matched column)
Vehicle5 (Reason: 1 matched column)
Vehicle3 (No matched column)
我的数据库在SQL服务器上。
答案 0 :(得分:2)
尝试这样的事情
SELECT Name + ' (Reason: '+CAST(MatchCount AS VARCHAR)+' matched columns)'
FROM (
SELECT NAME,(CASE WHEN VehicleMileage ='30HP@2000' THEN 1 ELSE 0 END +
CASE WHEN VehicleAverage='25000' THEN 1 ELSE 0 END +
CASE WHEN VehicleCC =1000 THEN 1 ELSE 0 END +
CASE WHEN Gear =3 THEN 1 ELSE 0 END ) AS MatchCount
FROM TableName
)t
ORDER BY MatchCount