假设我在SQL Server中有一个表Station
:
| ID | Name |
+------+------+
| 1 | a |
| 2 | b |
| 3 | cc |
| 4 | ddd |
| 5 | eee |
我想检索最短和最长的名称以及长度(如果是平局,它将按字母顺序显示前1)所以,输出将是
| a | 1 |
+-----+------+
| ddd | 3 |
我试过了:
Select
Name, len(name)
from
Station
where
len(name) = (Select min(len(name)) from Station)
union
Select
Name, len(name)
from
Station
where
len(name) = (Select max(len(name)) from Station)
但是,我必须先按字母顺序排在第一位,这是我无法做到的
答案 0 :(得分:1)
SELECT *
FROM
(SELECT TOP(1) *, LEN(name) as ln
FROM Student
ORDER BY ln, name
UNION
SELECT TOP(1) *, LEN(name) as ln
FROM Student
ORDER BY ln DESC, name) as tblMain
答案 1 :(得分:1)
select *
from (
select name
, row_number() over (order by len(name), name) rn1
, row_number() over (order by len(name) desc, name) rn2
from student
) sub
where rn1 = 1 -- Shortest name
or rn2 = 1 -- Longest name
答案 2 :(得分:1)
您的方法可以轻微调整:
Select min(Name) as name, len(name)
from Station
where len(name) = (Select min(len(name)) from Station)
group by len(name)
union all
Select min(Name) as name, len(name)
from Station
where len(name) = (Select max(len(name)) from Station)
group by len(name);
或:
Select min(Name) as name, min(len(name))
from Station
where len(name) = (Select min(len(name)) from Station)
union all
Select min(Name) as name, min(len(name))
from Station
where len(name) = (Select max(len(name)) from Station) ;
也就是说,通过聚合,你得到一行。