如何选择去年没有贡献的恩人(SQL)

时间:2014-12-10 08:52:05

标签: sql ms-access

我有一个简单的数据库,可以跟踪慈善组织的捐款(捐款)。

就本问题而言,我只需提及所涉及的两个表:contributionsbenefactors

捐助人:

ID | BenefactorName | AssociatedFundraiser | Other Meta Columns
-------------------------------------------------------------------
99 | ABC Accounting | 12                   | ...

内容:

ID  | ContributionDate | BenefactorID | Other Meta Columns
--------------------------------------------------------------
603 | 2014-09-29       | 99           | ...

该数据库中的许多捐助者不止一次做出贡献;主要是每月一次。但是,我想指出那些去年没有做出贡献的捐助者。

我该怎么做?

我尝试了各种INNER JOIN内容,但是偏离了轨道。

6 个答案:

答案 0 :(得分:1)

由于Access不支持MINUS集合运算符,因此在这种情况下,事情可能会有些混乱。我认为这样的查询可以满足您的需求:

SELECT v.ID, v.[Benefactor Name], v.MaxContributionDate
FROM (
    SELECT b.ID, b.[Benefactor Name], mx.MaxContributionDate
    FROM benefactors b
    INNER JOIN (
        SELECT MAX([Contribution Date]) AS MaxContributionDate, [Benefactor ID]
        FROM contributions
        GROUP BY [Benefactor ID]
    ) mx ON (mx.[Benefactor ID] = b.ID)
) v
LEFT JOIN (
    SELECT DISTINCT [Benefactor ID]
    FROM contributions
    WHERE Year([Contribution Date]) = 2014
) t ON (t.[Benefactor ID] = v.ID) 
WHERE t.[Benefactor ID] IS NULL;

“在线”查询查找为今年做出贡献的捐助者的明确列表,以及LEFT JOIN,其中密钥IS NULL确保我们只返回 <的捐助者这个集合中的em> not

编辑添加了额外的联接,以获取每位捐助者的最新投稿日期。

答案 1 :(得分:0)

SELECT b.*
FROM Benefactors b
INNER JOIN Contributions c ON b.id = c.BenefactorID
WHERE c.ContributionDate < DATEADD(year,-1,GETDATE())

答案 2 :(得分:0)

SELECT *
FROM benefactors AS b
WHERE (SELECT COUNT(*) 
       FROM contributions AS c 
       WHERE b.ID = c.benefactorID 
             AND c.ContributionDate < DATEADD(year,-1,GETDATE())
      ) = 0 

答案 3 :(得分:0)

使用LEFT JOIN.

获取过去一年没有捐款的捐助者名单。

SELECT A.* FROM Benefactors AS B 
LEFT JOIN Contributions AS C 
ON B.ID  = C.BenefactorID  AND C.BenefactorID IS NULL 
WHERE C.ContributionDate < DATEADD(year,-1,GETDATE())

答案 4 :(得分:0)

试试这个

   select * from Benefactors b where b.ID not in  (select BenefactorID  from Contributions where  datepart(yy,ContributionDate)=datepart(yy,getdate())-1 )

OR

 select * from Benefactors b inner join  (select * from Contributions where  datepart(yy,ContributionDate)=datepart(yy,getdate())-1 ) a on b.ID<>a.BenefactorID  

答案 5 :(得分:0)

如果您想选择去年没有做出任何贡献的捐助者列表(当前年份= 2014年,那么去年= 2013年)请尝试以下代码:< / p>

SELECT * FROM Benefactors 
WHERE ID NOT IN
 (SELECT BenefactorID FROM Contributions 
 WHERE DATEPART(yyyy, ContributionDate)  >
       DATEPART(yyyy, DATEADD(year,-2,GETDATE()))
 AND DATEPART(yyyy, ContributionDate) < DATEPART(yyyy, GETDATE())