多列的SQL Max Length(总计组合)

时间:2014-05-01 10:20:40

标签: sql max

我是非常新的SQL,需要一些建议。我会保持简短

我有3个地址列,它们具有固定的最大长度:

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

我需要查询才能找到最长的完整地址(Add1 + Add2 + Add3的组合)

我曾尝试使用以下内容,但我认为它给我的只是它们的maxlength值,所有这些都是单独的列,我知道是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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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可以为null,则可以使用以下内容:

coalesce(trim(add_1),'')

处理。

如果您的DBMS支持公用表表达式(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
相关问题