如何将字段更新为多个表/行的最长字符串?

时间:2014-05-12 17:13:57

标签: sql tsql

我试图合并"最佳"从两个表到第一个表的数据,但我无法弄清楚如何在set语句中选择最佳数据。

在这种情况下,"最好"数据意味着最长的"。 Table1具有唯一ID,但Table2具有ID的重复项。信息基本相同,但我想要Table1或Table2中字符串最长的字段,可能不是全部来自同一行。

我首先尝试了这一点,但当然,当Table2中有两个匹配的行时,合并失败:

USE DatabaseName
MERGE Table1 AS a
USING Table2 AS b1
ON a.[ID-unique] LIKE b1.[ID-not-unique]
WHEN MATCHED THEN UPDATE
SET a.[Field1] =
    CASE 
        WHEN a.[Field1] IS NULL
            THEN b1.[Field1]
        WHEN LEN(a.[Field1]) < LEN(b1.[Field1])
            THEN b1.[Field1]
        ELSE a.[Field1] END,
a.[Field2] =
    CASE
        WHEN a.[Field2] IS NULL
            THEN b1.[Field2]
        WHEN LEN(a.[Field2]) < LEN(b1.[Field2])
            THEN b1.[Field2]
        ELSE a.[Field2] END;

我在其他地方使用了类似的东西来选择最长的字符串,但是当我尝试将其包含为&#34;那么&#34;语句:

SELECT [Field] FROM Table2 b2
WHERE 
        LEN([Field])
        =   
        (
        SELECT MAX(LEN([Field]))
        FROM [Table2] AS b3
        WHERE b2.[ID-not-unique] = b3.[ID-not-unique]
        )

2 个答案:

答案 0 :(得分:1)

试试这个:

UPDATE T1
SET T1.Field = CASE 
                    WHEN LEN(T1.Field) < LEN(T2.Field) THEN T2.Field 
                    ELSE T1.Field 
                END
FROM Table1 T1
OUTER APPLY (SELECT TOP 1 *
             FROM Table2
             WHERE [ID-not-unique] = T1.[ID-unique]
             ORDER BY LEN([Field]) DESC) T2

答案 1 :(得分:0)

UPDATE T1
   SET T1.Field = T2.Field 
  FROM Table1 T1
  JOIN Table2 T2
    ON T2.[ID-not-unique] = T1.[ID-unique]
   AND len(T1.Field) < len(T2.Field)