SQL Query查找MAX Date

时间:2014-08-01 14:54:33

标签: sql dbase

我有一些软件使用dBase4作为其数据库。我正在尝试使用3个表(客户,服务和历史记录)中的字段构建报告。

在所有表格中,ACCOUNT字段都相同。 “客户”和“服务”表每个客户只有一条记录。 “历史记录”表为每个客户提供多条记录。

我需要编写一个查询,以便每个客户只返回“History.BILLTHRU”中具有MAX日期的记录。下面的代码返回History表中每个Customer的所有记录:

SELECT Customer.ACCOUNT, 
       Customer.FIRSTNAME, 
       (more fields...), 
       History.ACCOUNT, 
       History.BILLTHRU, 
       Service.ACCOUNT, 
       Service.OFFERCODE

FROM "C:\Customer.dbf" Customer

INNER JOIN "C:\History.dbf" History 
ON (Customer.ACCOUNT = History.ACCOUNT)

INNER JOIN "C:\Service.dbf" Service 
ON (Customer.ACCOUNT = Service.ACCOUNT) 

WHERE Customer.STATUS = "A" 
ORDER BY Customer.LAST_BUS_NAME 

2 个答案:

答案 0 :(得分:1)

使用子查询和分组:

SELECT Customer.ACCOUNT, 
       Customer.FIRSTNAME, 
       (more fields...), 
       History.ACCOUNT, 
       History.BILLTHRU, 
       Service.ACCOUNT, 
       Service.OFFERCODE

FROM "C:\Customer.dbf" Customer

INNER JOIN (SELECT ACCOUNT, MAX(BILLTHRU) AS BILLTHRU
            FROM "C:\History.dbf"
            GROUP BY ACCOUNT) History
ON (Customer.ACCOUNT = History.ACCOUNT)

INNER JOIN "C:\Service.dbf" Service 
ON (Customer.ACCOUNT = Service.ACCOUNT) 

WHERE Customer.STATUS = "A" 
ORDER BY Customer.LAST_BUS_NAME 

答案 1 :(得分:0)

我喜欢使用公用表表达式(CTEs)。子查询很好,但是像这样拆分它有时会更容易保持分离。

with GetMaxDate as (

select account, max(billthru) as MaxBillThru
       from  "C:\History.dbf"
       group by account
)

SELECT Customer.ACCOUNT, 
       Customer.FIRSTNAME, 
       (more fields...), 
       GetMaxDate.ACCOUNT, 
       GetMaxDate.MaxBillThru,
       Service.ACCOUNT, 
       Service.OFFERCODE
       .....
from FROM "C:\Customer.dbf" Customer

INNER JOIN GetMaxDate on customer.ACCOUNT = GetMaxDate.Account
INNER JOIN "C:\Service.dbf" Service 
ON (Customer.ACCOUNT = Service.ACCOUNT) 

WHERE Customer.STATUS = "A" 
ORDER BY Customer.LAST_BUS_NAME 

编辑:这是一个SQL Server功能。我离开它以防它可以帮助你或其他人。如果只是为了解决问题,我会删除它。

相关问题