【问题标题】:Using Substring to Identify Records and Update Records使用子字符串识别记录和更新记录
【发布时间】:2012-04-12 19:40:25
【问题描述】:

我的销售代表通过客户邮政编码的前三位数字与其客户相关联 - 这仅适用于美国客户。 Profile_Zip 表有两列 Profile_Key 代表 Rep 和 Three_Digits 代表邮政编码的前三位。

 Profile_Key      Three_Digits
 123456            610
 123456            611
 123456            612

Profile 表中保存客户记录的两个字段是 Zip(邮政编码)和一个保存销售代表 Profile_Key 的 Association 字段。

我需要运行一个查询,使用 Profile_Zip 表中代表的配置文件密钥更新客户的关联密钥。这就是我一直在使用的。

 update profile set association_key = 
 (select profile_key from profile_zip where three_digits = 
 (Select substring(zip, 1, 3) as ZipPrefix
 From profile group by profile.zip))

我知道为什么会出现此错误,但我不知道如何使查询正常工作,或者 Substring 是否是正确/最佳的选择。

子查询返回超过 1 个值。当子查询跟随 =、!=、、>= 或使用子查询时,这是不允许的 作为表达式。

还有其他方法可以做到这一点吗? 谢谢。

配置文件表。 John Doe 是代表 (profile_type = 4),Mary 是客户 (profile_type = 6)。 John 的 profile_key 在 Mary 的 Association_key 字段中,这就是绑定它们的原因。记录中当然还有更多字段(地址、电话等)

 Profile_key    Profile_Type_Key  First_Name   Last_Name   Zip    Association_Key  ...
  123456              4            John            Doe     92112    
  987654              6            Mary            Smith   90210     123456

【问题讨论】:

    标签: sql substring


    【解决方案1】:

    我认为这可以满足您的需求:

    UPDATE P
    SET Association_Key = PZ.Profile_Key
    FROM [Profile] P
    INNER JOIN Profile_Zip PZ
        ON PZ.Three_Digits = SUBSTRING(P.Zip, 1, 3)
    

    问题是您试图将标量值设置为结果集。在这种情况下,您希望更新结果集,然后使用正确的标量值。

    【讨论】:

      【解决方案2】:

      错误

      Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

      表示您在需要使用IN 时使用=。当使用= 时,系统只期望 1 个结果。

      特别是,我猜:

      Select substring(zip, 1, 3) as ZipPrefix
      From profile
      group by profile.zip
      

      返回大量子字符串。在这个子查询之外使用IN

      【讨论】:

      • 不,你错了。不是那种情况。请作者发布所有相关表的结构,就像您为 Profile_Zip 所做的那样
      • 您能否分享有关您的表结构和数据的其他信息?
      猜你喜欢
      • 2018-12-07
      • 2014-06-08
      • 1970-01-01
      • 2020-08-01
      • 2014-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多