简体   繁体   English

比较同一表中的两个值

[英]Comparing two values in the same table

I have a table which I would like get all the names of someone who's salary is less than then the next person in the same table, I have tried this but its not working any suggestions? 我有一个表格,我想获得一个薪水少于同一表格中下一个人的人的所有姓名,我已经尝试过此方法,但是它没有任何建议吗?

select t1.Name, t2.Name as Name2 
from employees t1 
inner join employees t2 on 
t1.ID = t2.ID
where t1.Salary < t2.Salary;

I am trying to print out the names of each person that has a lesser salary then the next for example 我正在尝试打印每个人的姓名,这些人的薪水比第二名的要少。

Joe "has less then" Bob
Joe "has less then" foo
Joe "has less then" Bar
Joe "has less then" Pete

Compare your current and next id column 比较您当前和下一个ID列

select t1.Name, t2.Name as Name2 ,t1.salary,t2.salary
from employees t1 
inner join employees t2 on 
t1.ID+1 = t2.Id
where t1.Salary < t2.Salary;

You are joining on the same ID. 您正在加入相同的ID。 You are comparing the salary of the same person. 您正在比较同一个人的薪水。

Try this: 尝试这个:

select t.LastName
from (
    select Name, 
    Salary, 
    @last_name AS LastName, 
    @last_sal AS LastSal, 
    @last_name := Name , 
    @last_sal := Salary 
    from employees
    cross join (select @last_name := NULL, @last_sal := NULL) param
    ) t
where t.LastSal < t.Salary;

select t1.Name || " has less then " || t2.Name from employees t1, employees t2 where t1.Salary < t2.Salary;

if you remove the inner join (resulting join will be a cross join) in that (I believe) you will be able to find what you are looking for. 如果您在其中删除内部联接(结果联接将是交叉联接),您将能够找到所需的内容。

PS: the query is not tested on any database schema, however it will work, m not sure on the concatenation syntax though. PS:该查询未在任何数据库模式上进行测试,但是可以使用,但不确定在连接语法上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM