2016-05-27 76 views
0

我有Customers表,我想拔出最短和最長的客戶名稱二階meged查詢

我不喜歡這樣寫道:

(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 

但它給我這個錯誤:Syntax error in JOIN operation.

我怎麼能這樣做?

+1

我甚至都沒有在您共享的源代碼中看到「JOIN」 –

回答

1
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