查询两个不同表的结果

时间:2014-04-24 17:55:43

标签: sql select join

我尝试编写查询以从两个或更多表中生成数据集,并且我在编写查询时遇到问题。我很高兴我在SQL中缺乏知识。

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

表1和表2可以与名为acct_id的列中包含的值结合使用。

我希望查询只显示acct_ids,其中帐户状态(acct_status)为"有效"来自表1,并且没有"活跃的"表2中的合同。

问题在于,在表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。

4 个答案:

答案 0 :(得分:1)

选择acct_id 来自table1 其中acct_status =“活跃”和       acct_id不在(从table2中选择acct_id,其中contract_status =“active”)

答案 1 :(得分:1)

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')

答案 2 :(得分:0)

通过使用IN来避免LEFT OUTER JOIN和子选择的恐怖:

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

答案 3 :(得分:0)

如果OBJECT_ID(N'tempdb .. #Customer',N'U')不是空丢弃表#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

中选择*

GO

如果OBJECT_ID(N'tempdb .. #Contcts',N'U')不是空丢弃表#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))