如何连接两个不同的select语句以返回任何匹配结果?

时间:2019-04-01 16:30:17

标签: sql sql-server

我有两个带有帐户信息的表。表1具有帐户类型和帐号。表2具有帐户名称和帐户状态。我想根据条件(即AccountNumber ='100'或'300')从Table1返回一个帐户列表,并将其加入与Table2中条件匹配的记录(即AccountStatus ='active')。

表1

AccountType - School
AccountType - School
AccountType - School
AccountNumber - 100
AccountNumber - 200
AccountNumber - 300

表2

AccountName - Tuition Expense
AccountName - Car Expense
AccountName - Food Expense
AccountStatus - Active
AccountStatus - Inactive
AccountStatus - Active

帐号-100 帐号-200 帐号-300

所以我可以退货(帐户为“ 100”或“ 300”,并且为“有效”):

表3

AccountType - School
AccountType - School
AccountNumber - 100 
AccountNumber - 300
AccountName - Tuition Expense
AccountName - Food Expense
AccountStatus - Active
AccountStatus - Active

SELECT Table1.AccountNumber
FROM Table1
WHERE Table1.AccountNumber IN ('100', '300') INNER JOIN
      Table2
      ON Table1.AccountNumber = Table2.AccountName
WHERE Table2.AccountStatus = 'ACTIVE'

1 个答案:

答案 0 :(得分:0)

除非两个表中都有一个公共字段,否则不能将表1与表2连接起来。您是否还有其他要在此处发布的表格?