在不使用top的情况下找到薪水最高的前2名员工

时间:2012-05-23 14:32:51

标签: mysql sql database

找到薪水最高的前2名员工。

表名为salary,列为name,salary

我们可以使用limit命令作为

来执行此查询
select * from salary order by salary DESC limit 0,2

但如何在不使用top和limit的情况下执行此操作?

8 个答案:

答案 0 :(得分:4)

我相信这个面试问题试图引导你进入嵌套选择,或常见的表格表达式,或类似的东西。 TOP 2是一个简单的答案,显然TOP就是为了这个目的而实施的 - 面试要求你“手动”完成。

理论代码。在第一行(嵌套)选择中为每一行提供行计数,然后从行数小于所需行数的行的结果中选择,在这种情况下为3。

MySQL - Get row number on select

嵌套选择(伪代码):

select row_count, * from salary order by salary desc

外部选择:

select * from <nested select> where row_count < 3

对不起,这不是MySQL代码,但我只知道SQL Server。

我有一些使用行计数的SQL Server代码:

declare @Salaries table
(
   id int,
   salary money
)

insert into @salaries (id, salary)
values (1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 4)  -- A duplicating salary

;WITH Props AS
(
    SELECT *,
        ROW_NUMBER() OVER (ORDER BY salary desc) AS RowNumber
    FROM @Salaries
)
SELECT * FROM Props WHERE RowNumber < 3

返回ID为4和5的行。


解决Sachin Kainth的回答

我相信这个答案是不正确的。请尝试以下SQL Server代码:

declare @Salaries table
(
   id int,
   salary money
)

insert into @salaries (id, salary)
values (1, 1),
(2, 2),
(3, 3),
(4, 4),
(5, 4)

select * from @salaries where salary in -- "in" introduces the problem
(
SELECT MAX(E1.Salary)  
FROM @salaries E1, @salaries E2
WHERE E1.Salary < E2.Salary

union

SELECT MAX(Salary)  
FROM @salaries
)

这将返回ID为3,4和5的行。而不仅仅是4和5.这是因为带有子句where salary in的外部select将采用第3,4和5行,这些行都返回了工资通过嵌套选择(返回工资值3和4)。

答案 1 :(得分:1)

根据SQL:2008标准,您可以将FETCH FIRST 10 ROWS ONLY附加到查询中。虽然,我从未尝试过这个。所以在你的情况下你会有

SELECT * FROM salary ORDER BY salary DESC FETCH FIRST 2 ROWS ONLY

答案 2 :(得分:1)

这是在MySQL:

SET @row := 0;
SELECT name, salary FROM
(SELECT name, salary, @row := @row + 1 AS Row FROM salary ORDER BY salary DESC)
  AS derived1
WHERE Row < 3

还有一个警告。如果工资有重复,结果可能会有所偏差。如果结果集大于两行,则结果将不包括在结果中,但由于问题是针对薪水最高的两名员工而不是薪水最高的两名员工,这是我能做的最好的。

也许正确的答案是问:“如果工资重复,我该怎么办?”

如果绝对必须是单个查询,那么这就是诀窍:

SELECT name, salary FROM
(SELECT name, salary, @row := @row + 1 AS Row FROM (SELECT @row := 0) AS d1, salary)
  AS d2
WHERE Row < 3

答案 3 :(得分:0)

select * from salary where salary in
(
SELECT MAX(E1.Salary)  
FROM Salary E1, Salary E2
WHERE E1.Salary < E2.Salary

union

SELECT MAX(Salary)  
FROM Salary
)

答案 4 :(得分:0)

+------+
| Sal  |
+------+
| 3500 | 
| 2500 |
| 2500 | 
| 5500 |
| 7500 |
+------+

以下查询将返回第N个最大元素。

select SAL from EMPLOYEE E1 where 
 (N - 1) = (select count(distinct(SAL)) 
            from EMPLOYEE E2 
            where E2.SAL > E1.SAL )

答案 5 :(得分:0)

  

表格结构

ArrayList<Items> itemsArrayList = new ArrayList<Items>();    
for(int j=0; j<imagesArray.length(); j++)
                        {
                        JSONObject imagesObject = imagesArray.getJSONObject(j);

                    items = new Items();
                    items.setTitle(imagesObject.getString("title"));
                    items.setImage(imagesObject.getString("image"));                                

                    itemsArrayList.add(items);
                }
  

第n个术语的mysql查询n表示第n个项目

DataSource dataSource;

@Override
public void injectServices(ServiceRegistryImplementor serviceRegistry) {
    Map lSettings = serviceRegistry.getService(ConfigurationService.class).getSettings();
    System.out.println("  ********************** " + Environment.DATASOURCE );
    System.out.println("  ********************** " + lSettings.get( Environment.DATASOURCE ) );
    dataSource = (DataSource) lSettings.get( Environment.DATASOURCE );

}

@Override
public boolean isUnwrappableAs(Class unwrapType) {
    // TODO Auto-generated method stub
    return ConnectionProvider.class.equals( unwrapType ) 
            ||  MultiTenantConnectionProvider.class.equals( unwrapType ) 
            || MultiTenantConnectionProviderImpl.class.isAssignableFrom( unwrapType );
}

@Override
public <T> T unwrap(Class<T> unwrapType) {
    // TODO Auto-generated method stub
    if ( isUnwrappableAs( unwrapType ) ) {
        return (T) this;
    }
    else {
        throw new UnknownUnwrapTypeException( unwrapType );
    }
}

@Override
public Connection getAnyConnection() throws SQLException {
    // TODO Auto-generated method stub  
    System.out.println("=== Get any connetion === ");
    try {
        dataSource.getConnection();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return dataSource.getConnection();
}

@Override
public Connection getConnection(String tenantId) throws SQLException {
    // TODO Auto-generated method stub
    System.out.println("=== Get connetion === ");
    System.out.println("=== Tenant ID = "+tenantId);
    return getAnyConnection();
}

@Override
public void releaseAnyConnection(Connection connection) throws SQLException {
    // TODO Auto-generated method stub
    System.out.println("=== releaseAnyConnection=== ");
    try {
        connection.close();
    }catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

@Override
public void releaseConnection(String tenantId, Connection connection)
        throws SQLException {
    // TODO Auto-generated method stub
    System.out.println("=== releaseConnection=== ");
     try {
            this.releaseAnyConnection(connection);
     }catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

@Override
public boolean supportsAggressiveRelease() {
    // TODO Auto-generated method stub
    System.out.println("=== supportsAggressiveRelease=== ");
    return false;
}

答案 6 :(得分:0)

SELECT e1.EmployeeID, e1.LastName, COUNT(DISTINCT e2.EmployeeID) AS sals_higher
FROM Employees e1
INNER JOIN Employees e2 ON e1.EmployeeID < e2.EmployeeID
GROUP BY e1.EmployeeID
HAVING sals_higher <= 2
ORDER BY e1.EmployeeID DESC

访问https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_union3 并尝试给定的代码片段,它为您提供前2个最大EmployeeID。

答案 7 :(得分:0)

`我认为这可能有用

    select * from salary s1 where 2>=(select count(distinct id) from salary s2
 where s1.salary<=s2.salary) order by salary desc;

这是共同相关的查询。对于外部查询中的每一行,内部查询将运行并通过将外部查询的工资值与表中的每个工资进行比较来返回计数值。 它就像一个嵌套的编程语言循环

假设我们有两个列id和工资

的表薪水
id Salary
1  1200
2  12345
3  123456
4  2535436 

输出

id salary
4  2535436
2  123456