基于另外两个表过滤记录

时间:2013-10-02 18:50:55

标签: sql ms-access join subquery ms-access-2010

我需要在MS Access数据库中生成活动客户列表。所有过去和现在的客户都存储在客户表中。但是,确定活动状态的标准需要从另外两个表中得出:进入和退出。如果客户的入职日期之后没有退出日期,则该客户被视为有效。然而,为了混淆事物,具有退出日期的前顾客可以通过获得新的入口日期再次成为顾客。

以下是存储此信息的三个表结构的相关部分:

customers table  
    customerID  
    name  

intake table  
    intakeID  
    customerID  
    intakeDate  

exit date  
    exitID  
    customerID  
    exitDate  

客户可以拥有多个进气记录和多个退出记录。因此,SQL语句的伪代码需要看起来像:

SELECT customerID, name FROM customers  
WHERE ((most recent intakeDate)>(most recent exitDate(if any)))

在真正的SQL中它应该是什么样的?对于MS Access 2010数据库。显然,连接是必要的。但是什么类型的连接?它需要怎样看?

3 个答案:

答案 0 :(得分:1)

SELECT ActiveCustomers.*, tblAddress.* FROM 
(
  SELECT customers.name, customers.customerID,
  (
    SELECT COUNT(intakeDate) 
    FROM intake 
    WHERE customers.customerID = intake.customerID AND Len(intakeDate & '') > 0
  ) AS IntakeCount,
  (
    SELECT COUNT(exitDate) 
    FROM exit 
    WHERE customers.customerID = exit.customerID AND Len(exitDate & '') > 0
  ) AS ExitCount
  FROM customers 
) AS ActiveCustomers
INNER JOIN tblAddress ON ActiveCustomers.customerID = tblAddress.customerID
WHERE IntakeCount > ExitCount
AND tblAddress.CurrentAddress = True

答案 1 :(得分:1)

select * from 
    (SELECT  CustomerID, Name, MAX(intakeDate) AS intakeDate, MAX(exitDate) AS exitDate
    FROM  customerstable 
    INNER JOIN intaketable 
    ON customerID = customerID 
    INNER JOIN  exitdate 
    ON intaketable.customerID = exitdate.customerID
    GROUP BY dbo.customerstable.CustomerID ) c
where intakeDate > exitDate

答案 2 :(得分:1)

我喜欢@sqlgrl的方法,只关注每个客户的最新进入和退出,但我已经调整它以使用特定于MS Access的语法,而且,我认为,稍微加强了连接逻辑:< / p>

select c.*
from ([customers table] as c
inner join (
  select customerID, max(exitDate) as lastOut
  from [exit date]
  group by customerID
) as [out]
on c.customerID = [out].customerID)
inner join (
  select customerID, max(intakeDate) as lastIn
  from [intake table]
  group by customerID
) as [in]
on c.customerID = [in].customerID
where [in].lastIn > [out].lastOut

以上基本上说:

  • 建立每个客户最近退出日期的列表
  • 建立每个客户最近入学日期的清单
  • 使用customers表加入两个列表
  • 如果客户的最近入学日期是在最近的退出日期之后,请将此客户包含在最终输出中