0

我有两个要查询客户和服务的表

客户表

    cnum       lastName        Address       Phone        Comments      

     2         McKenzie        Main Street   1234567898   None
     3         Stevenson       South Street  1225448844   None
     4         Adams           North Street  1234545454   None

服务

     IncidentNum     cnum      serviceDate      status       category      LastUpdated

     x1               2        02-21-2013       Closed       Repair        02-21-2013
     c2               2        05-12-2013       Open         Installation  05-13-2013
     d2               3        05-01-2013       Closed       Repair        05-05-2013
     f2               4        05-12-2013       Open         Repair        05-12-2013

基本上我想要做的是显示每个客户记录的最新更新记录,无论状态是关闭还是打开。

最后:

    cnum    lastName     Address        Phone        Category       Last Service
     2      McKenzie     Main Street    1234567898   Installation   05-13-2013
     3      Stevenson    South Street   1225448844   Repair         05-05-2013
     4      Adams        North Street   1234545454   Repair         05-12-2013

我使用 OLEDB,这是我在 VB 中的项目。任何输入将不胜感激。先感谢您!

4

3 回答 3

0
select distinct customer.cnum,customer.lastname,customer.address,customer.phone,
service.category,
MAX(lastupdated)as lastservice from service,customer where service.cnum=customer.cnum
and service.servicedate = ( select max(serviceDate) from service service2
                            where service2.cnum = customer.cnum)
group by customer.cnum,customer.lastname,customer.address,customer.phone,
service.category

我希望这就是你要找的。我对其进行了测试,它给出了您在问题中提到的确切输出。

于 2013-05-14T01:59:07.523 回答
0

这很简单.. 看到您必须在 * cnum * 上加入这两个表,然后最重要的是您可以设置最新/最大服务日期的条件..

您可以对同一任务使用以下查询 -

select customer.cnum,
       customer.lastname,
       customer.address,
       customer.phone,
       service.category,
       service.servicedate 
  from customer,service
 where customer.cnum = service.cnum
   and service.servicedate = ( select max(serviceDate) from service service2
                                where service2.cnum = customer.cnum)

我希望这就是你要找的..

编辑:编辑查询以显示服务表中不存在的客户信息

select customer.cnum,
       customer.lastname,
       customer.address,
       customer.phone,
       service.category,
       service.servicedate 
  from customer left outer join service on (customer.cnum = service.cnum)
   where (service.servicedate = ( select max(serviceDate) from service service2
                                where service2.cnum = customer.cnum)
          or service.cnum is null)
于 2013-05-13T20:36:27.907 回答
0

你能试试这个吗?

select c.cnum, c.lastname, c.address,
c.phone, s.category, s.servicedate 
from customer c,service s
where c.cnum = s.cnum
group by c.cnum
having s.LastUpdated = max(s.LastUpdated)
于 2013-05-13T21:18:36.740 回答