如何从DataBase获取给定输入的最接近匹配值

时间:2016-06-27 06:46:08

标签: sql performance postgresql

我正在尝试构建一个SQL查询,它将获取给定值的最接近匹配,当用户给出输入8000时,我想获取最接近8000的一条记录,一条等于8000的记录和一条记录哪个级别高于8000.设计数据模型的最佳方法是什么,SQL进行此操作,我试图通过单个查询最小化这个以获得性能,请建议。

请考虑以下示例,其中Employee是表名和名称,salary是其属性

创建表employee(名称文本,工资整数)

这是Employee表的示例数据

 Name  | salary
 ----------
 Raju         5000
 Ram          8000
 Sulthan      7000
 Aditya       10,000

正如我在上面解释的那样,如果我输入工资为8000,我想获取一条最接近8000的记录,一条等于8000的记录和一条高于8000的记录

1 个答案:

答案 0 :(得分:0)

您可以使用窗口功能执行此操作:

int[] score = new int[5];
int highScore = 0;
int sum = 0;
int ave = 0;

//Requests the user to input 5 numbers
Console.WriteLine("Please enter 5 test scores:");

//Obtains the input and sets the highScore as well as the sum for all the number entered

for (int i = 0; i < 5; i++)
{
    score[i] = Int32.Parse(Console.ReadLine());
    if (i > highScore)
    {
        highScore = i;
        sum += score[i];
    }
}

//Requests the user to enter the max score
Console.WriteLine("Please enter the max score:");
int maxScore = Int32.Parse(Console.ReadLine());

另一种选择是使用三个查询并将它们与select name, salary from ( select name, salary, case when salary = 8000 then 1 when lag(salary) over w = 8000 then 1 when lead(salary) over w = 8000 then 1 else 0 end as flag from employee window w as (order by salary) ) t where flag = 1;

组合
UNION ALL