SQL CASE WHEN 不满足条件

SQL CASE WHEN won't meet condition

select salary as SecondHighestSalary
from Employee
where salary = case 
    when (select count(*)
         from Employee) <= 1 then null
    when (
        select count(*)
        from Employee
    ) > 1 then (
        select salary
        from (select salary
              from Employee
              order by salary desc
              limit 2
        ) as two_highest_salary_table
        order by salary asc
        limit 1
    )
    end;

这是一个 leetcode 问题的解决方案。它要求我从 table 中输出第二高的薪水,如果没有第二高的薪水,那么输出应该为空。

以上是我的解决方法。我使用了 case 和 when 语法,但问题是即使 table 只有 1 行,它也不会输出带有 NULL 值的 table 但它只输出 table w什么都没有。

我该如何解决这个问题?

我觉得你有点复杂。

尝试:

SELECT MAX(Salary) as Salary
From Employee1 
WHERE Salary < ( SELECT Max(Salary) FROM Employee1);

Demo

就简单多了,如你所想,一个简单的SELECT加上LOT和OFFSET就够了

CREATE TABLE Employee (salary DECIMAL(10,2))
INSERT INTO Employee VALUES(10000.1)
select salary
              from Employee
              order by salary desc
              limit 1,2
| salary |
| -----: |
INSERT INTO Employee VALUES(20000.2)
select salary
              from Employee
              order by salary desc
              limit 1,2
|   salary |
| -------: |
| 10000.10 |

db<>fiddle here

如果您需要始终 return 如果没有符合条件的 second-highest 值,则需要使用 NULL 行,您需要外部连接到源行 - 这将允许您 return 所有如果需要列。

select Salary
from
(select 2 as s) choice
left join (
  select salary, dense_rank() over(order by salary desc) rnk
  from Employee
)s on  s.rnk = s;

Example Fiddle