【问题标题】:Is there a way to use SUBQUERY for a cascading where statement?有没有办法将 SUBQUERY 用于级联 where 语句?
【发布时间】:2019-11-05 17:29:38
【问题描述】:

我正在尝试附加一些虚拟数据作为参考。

我正在尝试从数十万的池中提取一组帐号。该池由潜在客户和关注客户组成。潜在客户帐户以 5 位数字开头,以三个零结尾。以下帐户使用相同的 5 个数字,并更改最后三个。每个潜在客户通常有 25-75 个关注帐户。

我的目标是从一组潜在客户中提取所有关注客户。 我面临的问题是以下帐户不包含我希望过滤掉的隐含标准。主要客户有一个颜色代码,所有后续客户都知道是在这个颜色代码下。不幸的是,这仅在领先时给出。

这是我目前所拥有的:

Select
    Account Number,
    Color Code
From
    Master.Table
Where
    LEFT(Account Number, 5) =
    (Select LEFT(Account Number, 5)
     From Master.Table
     Where Color Code IN ('Green', 'Magenta', 'Teal', 'Gray', 'Purple', 'Yellow', 'Beige'))

【问题讨论】:

  • 您应该将该段落添加到您的original question,而不是发布一个新段落。不过,建议保持不变,你有 id,所以left join 在他们身上。现在您已经定义了 id 的关联方式,连接条件为 on left(t1.id, 5) = left(t2.id, 5) and t1.id <> t2.id
  • 请标记您正在使用的数据库。您的查询有什么问题?

标签: sql


【解决方案1】:

您的代码基本上看起来是正确的。我会做一些小的修改:

Select t.AccountNumber, t.ColorCode
From Master.Table t
Where left(t.AccountNumber, 5) in (
           Select left(t2.AccountNumber, 5)
           From Master.Table t2
           Where t2.ColorCode in ('Green', 'Magenta', 'Teal', 'Gray', 'Purple', 'Yellow', 'Beige') and
                 t2.AccountNumber like '%000'
          );

注意事项:

  • 这会修正列名,使其没有空格。
  • 这使用IN 而不是=
  • 这可确保在子查询中仅考虑主帐户。

【讨论】:

    【解决方案2】:

    你也可以在没有子查询的情况下做一些事情,使用连接

    CREATE TABLE #tempTable (
        accountNumber NVARCHAR(20),
        colorCode NVARCHAR(20)
        )
    
    INSERT INTO #tempTable (
        accountNumber,
        colorCode
        )
    VALUES ('12345000','Magenta'),('12346000','Beige'),('12347000','Black'),
        ('12345123',''),('12346321',''),('12346387',''),('12347988','')
    
    SELECT b.accountNumber, a.colorCode
    FROM #tempTable a
    LEFT JOIN #tempTable b
        ON LEFT(a.accountNumber, 5) = LEFT(b.accountNumber, 5)
            AND a.colorCode IN (
                'Green',
                'Magenta',
                'Teal',
                'Gray',
                'Purple',
                'Yellow',
                'Beige'
                )
    WHERE RIGHT(b.accountNumber, 3) <> '000'
    
    DROP TABLE #tempTable
    

    这会返回

    accountNumber   colorCode
    12345123        Magenta
    12346321        Beige
    12346387        Beige
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-12
      • 2012-03-04
      • 1970-01-01
      相关资源
      最近更新 更多