简体   繁体   English

同一表中的相互匹配的SQL Server查询(2012)

[英]SQL Server Query for Mutual Matches in the same Table (2012)

We have a table with following columns in Tenants Table. 我们在租户表中有一个包含以下列的表。

TenantID
Name
address
Current_Bedrooms
Bedrooms_Needed
Current_City
City_Needed

For a given row, how can we write a query that will find the match the bedrooms_Needed with Current_Bedrooms (same with city) in other rows 对于给定的行,我们如何编写一个查询,该查询将找到其他行中的Houses_Bedrooms (与城市相同)的卧室_Needed

example

Select * from Tenants where Current_Bedrooms = Bedrooms_Needed and TenantID = 1234

It sounds like you want the tenants to 'swap' with eachother? 听起来你想让租户互相“交换”? You can join the tenants table with itself (aliased as t1 and t2 ), while specifying the matching criteria as the join condition: 您可以将租户表连接起来(别名为t1t2 ),同时将匹配条件指定为连接条件:

Select T1.Name As TenantFrom, t2.Name AS TenantTo
from Tenants t1
INNER JOIN Tenants t2
ON t1.Bedrooms_Needed = t2.Current_Bedrooms 
AND t1.City_Needed = t2.Current_City
AND t1.TenantID <> t2.TenantID
WHERE t1.TenantID = 1234;

The tenant id exclusion is to prevent self-matches in the event of the tenant living in an exact match already. 租户身份排除是为了防止租户已经完全匹配的情况下进行自我匹配。

Edit, Re Mutual Matches 编辑,相互匹配

In order to find pairs of mutually matching tenants, you will need to add the reciprocal criteria as additional filters: 为了找到相互匹配的租户对,您需要添加互惠标准作为额外的过滤器:

Select T1.Name As TenantFrom, t2.Name AS TenantTo
from Tenants t1
INNER JOIN Tenants t2
ON t1.Bedrooms_Needed = t2.Current_Bedrooms 
AND t1.City_Needed = t2.Current_City
AND t1.Current_Bedrooms = t2.Bedrooms_Needed
AND t1.Current_City = t2.City_Needed 
AND t1.TenantID <> t2.TenantID
WHERE t1.TenantID = 1234;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM