我有客户
表,我想提取最短和最长的客户名称
我这样做:
(SELECT TOP 1 CustomerName, LEN(CustomerName) AS LENGTH FROM Customers ORDER BY LEN(CustomerName) ASC, CustomerName ASC)
UNION
(SELECT TOP 1 CustomerName, LEN(CustomerName) AS LENGTH FROM Customers ORDER BY LEN(CustomerName) DESC, CustomerName ASC)
我得到了两个正确的结果,但现在我想按 LENGTH
列对它们进行排序。我试过这个:
SELECT * FROM
(
(SELECT TOP 1 CustomerName, LEN(CustomerName) AS LENGTH FROM Customers ORDER BY LEN(CustomerName) ASC, CustomerName ASC)
UNION
(SELECT TOP 1 CustomerName, LEN(CustomerName) AS LENGTH FROM Customers ORDER BY LEN(CustomerName) DESC, CustomerName ASC)
)
ORDER BY LEN(CustomerName) ASC
但它给了我这个错误:JOIN 操作中的语法错误。
我怎样才能做到这一点?
最佳答案
select customername,len(customername) as namelength
from (SELECT MAX(LEN(CustomerName)) AS MAXLENGTH, MIN(LEN(CustomerName)) AS MINLENGTH
FROM Customers) lens
join customers c on c.len(customername) = lens.maxlength or c.len(customername) = lens.minlength
order by namelength desc, customername
关于mysql - 订购两个合并查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37488699/