2015-10-30 27 views
1

我想選擇最短和最長的名稱,如果有多個名稱的長度相同,我應該得到第一個按名稱排序的名稱如何從SQL Server中的聚合方法獲取不同的值

例如,如果我有這些值:

'abc', 'def', 'abcd', 'defghi', 'ghi' 

我應該得到的東西像

abc 3 
defghi 6 

這是我的查詢

select 
    Name, LEN(Name) 
from 
    Customer 
where 
    len(Name) = (select min(len(Name)) from Customer) 
    or 
    len(Name) = (select max(len(Name)) from Customer) 
order by 
    Name; 

但這裏是我得到

abc 3 
def 3 
defghi 6 
ghi 3 

回答

5

我覺得這是最簡單的一個union alltop

select * 
from ((select top 1 c.* 
     from customer 
     order by len(name) desc, name 
    ) union all 
     (select top 1 c.* 
     from customer 
     order by len(name) asc, name 
    ) 
    ) t; 
+1

我相信這是正確的方法,但不是有效的SQL Server語法,所有派生表都需要一個別名,而且您還需要一個外部選擇,因爲即使子查詢有一個別名,這也會失敗。 – GarethD

+0

@GarethD。 。 。謝謝。有趣的是,我還沒有意識到SQL Server不支持'union' /'union all'語句中的圓括號。無論如何,我通常會用子查詢寫這樣的語句(如修改後的答案)。 –

1

隨着窗口的功能:

with cte as(select *, 
        row_number() over(order by len(name), name) rn1, 
        row_number() over(order by len(name) desc, name) rn2 
      from Customer) 
select name, len(name) from cte where rn1 = 1 or rn2 = 1 
0

您可以訂購它們的長度和名稱如下:

declare @data table(name varchar(10)) 
insert into @data(name) values('abc'), ('def'), ('abcd'), ('defghi'), ('ghi') 

Select name From (
    Select * 
     , small = ROW_NUMBER() over(order by len(name), name) 
     , big = ROW_NUMBER() over(order by len(name) desc, name) 
    From @data 
) t 
Where small = 1 or big = 1 
相關問題