MS Access帮助运行查询

时间:2019-01-24 10:25:15

标签: sql ms-access join

我有两个表格如下。enter image description here

我想获取所有活跃的会员,并且付款周期=每两周一次,以及每个会员在特定年份和月份的相应储蓄记录。请注意,某些成员可能没有给定年份和月份的储蓄记录。 我写了一个查询,但是它不返回在储蓄表中没有储蓄记录的成员。

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;

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