2014-05-01 60 views
1

即时通讯非常新,需要一些建议。我会保持它简短SQL最大长度(总合)多列

我有3个地址栏已经固定的最大长度:

Add1 - Max 30 
Add2 - Max 20 
Add3 - Max 20 

我需要一个查询来寻找最长完整地址(ADD1 + ADD2 + ADD3的组合)

使用以下,但我认为这是给我只是他们都作为单独的列,这是我知道的最大长度为30

SELECT MAX(len(T.Address)) AS MaxOfAddress 
FROM (
    SELECT add_1 AS Address 
    FROM table 
    UNION ALL 
    SELECT add_2 AS Address 
    FROM table 
    UNION ALL 
    SELECT add_2 AS Address 
    FROM table) AS T 

回答

1

这个怎么样我试过查询:

select 
    max(len(add_1)+len(add_2)+len(add_3)) Col 
from 
    table 

对于数据,请尝试:

select TOP 1 * 
From table 
order by len(add_1)+len(add_2)+len(add_3) desc 
+0

+1这是好的,但需要更多一些工作,因为他想要的实际地址不是其长度 – CodeBird

+1

@CodeBird请检查添加的答案。 – TechDo

+0

对它进行排序。非常感谢您的帮助。对于所有优秀的解决方案以及新用户的长时间答案,很大程度上受益于 – user3592268

1

的版本可能会与大多数DBMS的工作将是:

select add_1, add_2, add_3 
from T 
where length(trim(add_1)) + length(trim(add_2)) + length(trim(add_3)) 
    = (select max(len) 
     from (
     select 
     length(trim(add_1)) + length(trim(add_2)) + length(trim(add_3)) as len 
     from T 
     ) 
    ) 

如果add_n可以为空,你可以使用例如:

coalesce(trim(add_1),'') 

来处理。

如果您的DBMS支持Common Table Expressions(CTE),那么使用它可能会更高效。喜欢的东西:

with cte (add_1,add_2,add_3,len) as ( 
    select add_1,add_2,add_3 
     , length(trim(add_1))+length(trim(add_3))+length(trim(add_3)) from T 
) 
select add_1,add_2,add_3 
from cte 
where len = (select max(len) from cte) 

还有一种选择是,如果你的DBMS支持的分析功能,如ROW_NUMBER:

select add_1,add_2,add_3 
from (
    select add_1,add_2,add_3 
     , row_number() over ( 
      order by length(trim(add_1))+length(trim(add_3))+length(trim(add_3)) desc 
      ) as rn 
    from t 
) where rn = 1 

,或者你可以

select add_1,add_2,add_3 
from T 
order by length(trim(add_1))+length(trim(add_3))+length(trim(add_3)) desc 
fetch first 1 rows only 
+0

+1! – CodeBird