我正在创建一个存储过程,我希望每次匹配时只返回第一条记录而不是匹配的每条记录。
到目前为止,我编写了以下代码:
SELECT
Tenant.FirstNames AS LeadTenantFirstName, Tenant.LastNames AS LeadTenantLastNames,
Deposit.CertificateNumber AS DPCNumber
FROM tblMemberPropertyDepositTenantHistory AS Tenant
INNER JOIN tblMemberPropertyDeposits AS Deposit
ON Tenant.MemberPropertyDepositID = Deposit.MemberPropertyDepositID
问题是它会在查询证书时为每个租户带回一条记录,但我想带回为每个证书创建的第一个租户?
有什么想法吗?
答案 0 :(得分:2)
如果我理解你,你需要这样的东西:
;WITH CTE AS
(
SELECT
ROW_NUMBER() OVER(PARTITION BY Tenant.MemberPropertyDepositID ORDER BY Tenant.MemberPropertyDepositID) AS RowNbr,
Tenant.MemberPropertyDepositID,
Tenant.FirstNames,
Tenant.LastNames
FROM
tblMemberPropertyDepositTenantHistory AS Tenant
)
SELECT
Tenant.FirstNames AS LeadTenantFirstName,
Tenant.LastNames AS LeadTenantLastNames,
Deposit.CertificateNumber AS DPCNumber
FROM
tblMemberPropertyDeposits AS Deposit
LEFT JOIN CTE AS Tenant
ON Tenant.MemberPropertyDepositID=Deposit.MemberPropertyDepositID
AND Tenant.RowNbr=1
答案 1 :(得分:0)
我假设tblMemberPropertyDepositTenantHistory(存款)有一个主键:
SELECT
Tenant.FirstNames AS LeadTenantFirstName, Tenant.LastNames AS LeadTenantLastNames,
Deposit.CertificateNumber AS DPCNumber
FROM tblMemberPropertyDepositTenantHistory AS Tenant
INNER JOIN tblMemberPropertyDeposits AS Deposit
ON Deposit.PrimaryKey = (
SELECT MIN(tblMemberPropertyDepositTenantHistory.PrimaryKey)
FROM tblMemberPropertyDepositTenantHistory
WHERE tblMemberPropertyDepositTenantHistory.MemberPropertyDepositID =
Tenant.MemberPropertyDepositID
)