0

我需要在 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 数据库。显然,连接是必要的。但是什么类型的连接呢?它需要看起来如何?

4

3 回答 3

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
于 2013-10-02T18:59:15.723 回答
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
于 2013-10-02T19:09:17.880 回答
1

我喜欢@sqlgrl 的方法,即只查看每个客户最近的进出,但我已经对其进行了调整以使用特定于 MS Access 的语法,而且我认为还稍微加强了连接逻辑:

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

上面基本上说:

  • 建立每个客户最近退出日期的列表
  • 建立每个客户最近的摄入日期的列表
  • 将两个列表与客户表连接起来
  • 如果客户最近的进入日期是在他们最近的退出日期之后,则将此客户包括在最终输出中
于 2013-10-02T23:46:09.070 回答