根据值 - SQL 服务器仅获取包含返回行的一行

Get only one row with returned rows based on the value - SQL Server

我有一个 select 查询 returns 数据 a table 具有不同的 ID,见下文:

案例 1:

+--------+---------+
| RowNum |  Size   |
+--------+---------+
|      1 | large   |
+--------+---------+

案例二:

+--------+---------+
| RowNum |  Size   |
+--------+---------+
|      1 | small   |
|      2 | x-large |
+--------+---------+

案例 3:

+--------+---------+
| RowNum |  Size   |
+--------+---------+
|      1 | small   |
|      2 | small   |
|      3 | x-large |
|      4 | large   |
+--------+---------+

案例 4:

+--------+---------+
| RowNum |  Size   |
+--------+---------+
|      1 | large   |
|      2 | medium  |
|      3 | large   |
+--------+---------+

案例 5:

+--------+---------+
| RowNum |  Size   |
+--------+---------+
|      1 | small   |
|      2 | x-large |
|      3 | medium  |
|      4 | large   |
+--------+---------+

案例6、7、8.....

注意:所有返回的table可能有不同的行和值,所以可能是十种情况,行号只是一个没有意义的索引。

与 table 的行相比,我只需要返回最大的一行。

例如:

  1. 在案例 1 中,我只需要 'large' 行;
  2. 在案例 2 中,我只需要 'x-large' 行;
  3. 在案例 3 中,我只需要 'x-large' 行;
  4. 在案例 4 中,我只需要 'large' 行;
  5. 在案例 5 中,我只需要 'x-large' 行;

谁能帮我想办法得到结果?

解决方案可以是存储过程、函数、视图或查询。

非常感谢!

无论您可以使用 CASE 而不是 ORDER BY 的逻辑,只是为了回答演示问题

select top 1 *
from 
table
order by (
case size
   when 'x-large' then 4 
   when 'large' then 3
   when 'medium' then 2
   when 'small' then 1
   else 0
end
) desc