我想获取所有活跃的会员,并且付款周期=每两周一次,以及每个会员在特定年份和月份的相应储蓄记录。请注意,某些成员可能没有给定年份和月份的储蓄记录。 我写了一个查询,但是它不返回在储蓄表中没有储蓄记录的成员。
SELECT Member.memberID As [ID],Member.firstName AS [First Name],
Member.lastName AS [Last Name], Member.paymentPeriod AS [Payment Period],
Savings.savingId AS [Savings Id], Savings.enteredAmount AS [Amount]
FROM Member
LEFT JOIN Savings ON Member.memberID = Savings.memberId
WHERE Member.isActive = 'Active' AND Member.paymentPeriod = 'Fortnightly'
AND Year(Savings.enteredDate)=2019 AND Month(Savings.enteredDate) = 1;
答案 0 :(得分:1)
将SAVINGS
条件从WHERE
移到ON
以获得真实的LEFT JOIN
结果:
SELECT Member.memberID As [ID],Member.firstName AS [First Name],
Member.lastName AS [Last Name], Member.paymentPeriod AS [Payment Period],
Savings.savingId AS [Savings Id], Savings.enteredAmount AS [Amount]
FROM Member
LEFT JOIN Savings ON Member.memberID = Savings.memberId
AND Year(Savings.enteredDate)=2019 AND Month(Savings.enteredDate) = 1
WHERE Member.isActive = 'Active' AND Member.paymentPeriod = 'Fortnightly';
(有了WHERE
子句中的条件,您将获得常规的INNER JOIN
结果。)
编辑::尝试避免出现“ 不支持联接表达式错误”:
SELECT Member.memberID As [ID],Member.firstName AS [First Name],
Member.lastName AS [Last Name], Member.paymentPeriod AS [Payment Period],
Savings.savingId AS [Savings Id], Savings.enteredAmount AS [Amount]
FROM Member
LEFT JOIN Savings ON Member.memberID = Savings.memberId
WHERE Member.isActive = 'Active' AND Member.paymentPeriod = 'Fortnightly'
AND (Year(Savings.enteredDate)=2019 or Year(Savings.enteredDate) IS NULL)
AND (Month(Savings.enteredDate) = 1 or Month(Savings.enteredDate) IS NULL);