【问题标题】:Query Results from Two Different Tables从两个不同的表查询结果
【发布时间】:2014-04-25 03:53:34
【问题描述】:

我正在尝试编写查询以从两个或更多表中生成数据集,但我在编写查询时遇到了问题。对于我缺乏 SQL 知识,我深表歉意。

表 1 包含基本客户帐户信息,表 2 包含客户合同详细信息,其中一个客户帐户可以有多个合同,包括非活动和活动

表 1 和表 2 可以与包含在名为 acct_id 的列下的值连接。

我希望查询仅显示表 1 中帐户状态 (acct_status) 为“活动”且没有表 2 中的“活动”合同的 acct_ids。

问题在于,在表 2 中,与 acct_id 关联的合同不止一个,并且处于不同的状态。

如果我的 where 子句只关注表 2 中的合同状态值,我的数据集将不准确。它只会返回与这些值有合约的 acct_ids。

例如:

acct_iD 123 has 6 contracts: 1 active contract, 4 cancelled contracts, 1 cancel in progress contract

acct_ID 456 has 3 contracts: 3 cancelled contracts

acct_ID 789 has 4 contracts: 2 active contracts, 2 cancelled contracts

acct_ID 012 has 1 contract: 1 cancelled contract

我希望我的查询结果只显示 acct_IDs: 456 和 012,因为它真正表示它们没有“有效”合同

我正在使用 SQL Management Studio 2008 R2。

【问题讨论】:

  • 如果您提供子查询以获取您确实知道如何获取的部分,这将大大有助于加快回答速度。
  • 请附上您的代码。

标签: sql select join


【解决方案1】:

选择 acct_id 从表 1 其中 acct_status = "active" 和 acct_id 不在(从 table2 中选择 acct_id where contract_status = "active")

【讨论】:

  • 或者你可以使用连接。更清晰,这几乎就是发明连接的目的。
【解决方案2】:
SELECT A.*
FROM Table1 A
WHERE A.acct_status = 'active'
AND NOT A.acct_id in (SELECT acct_id FROM Table2 WHERE contract_status = 'active')

【讨论】:

    【解决方案3】:

    通过像这样使用LEFT OUTER JOINs 来避免IN 和子选择的恐惧:

    SELECT A.*
    FROM Table1 A
    LEFT OUTER JOIN table2 B
        ON b.acct_id = A.acct_id
        AND B.status = 'active'
    WHERE b.acct_id IS NULL
    

    【讨论】:

      【解决方案4】:

      IF OBJECT_ID(N'tempdb..#Customer', N'U') is not null drop table #Customer

      选择

      identity(int,1,1) as Customer_ID
      
      , 'John Doe, the Ranger' as name
      
      , '012' as Acct_ID
      
      , 1 as Active
      

      进入#Customer

      插入#Customer (name, Acct_ID, Active) 值('Kermit the Frog', '789',1)

      从#Customer中选择*

      IF OBJECT_ID(N'tempdb..#Contracts', N'U') is not null drop table #Contracts

      选择

      identity(int,1,1) as Contract_ID
      
      , 1 as Customer_ID
      
      , '012' as Acct_ID
      
      , 123.45 as amt
      
      , 1 as Active
      

      进入#Contracts

      插入#Contracts (Customer_ID, Acct_ID, amt, active) 值(1, '012', 234.56, 1)

      插入#Contracts (Customer_ID, Acct_ID, amt, active) 值 (2, '788', 9.56,1)

      插入#Contracts (Customer_ID, Acct_ID, amt, active) 值 (1, '789', 111.56, 0)

      从#Contracts A中选择*

      选择 *

      来自#Customer A

      其中 a.Active=1

      and (a.Acct_ID not in (select Acct_ID from #Contracts where Active=1))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-06-01
        • 2013-05-23
        • 2021-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-28
        相关资源
        最近更新 更多