0

我有两张桌子,

部分注销


PART_ID   DRAWN_DATE   LOCATION
 C0001    07/29/2013     501
 C0002    07/29/2013     604
 C0003    08/01/2013     703
 C0004    08/01/2013     807
 C0005    08/02/2013     505
 C0006    08/02/2013     602
 C0007    08/02/2013     707
 C0008    08/03/2013     802
 C0009    08/03/2013     803

零件退货


PART_ID   RETURN_DATE   LOCATION
 C0001    09/04/2013     STORE
 C0002    09/05/2013     STORE
 C0004    09/10/2013     STORE
 C0007    09/12/2013     STORE
 C0008    09/13/2013     STORE

这是我想要的结果:


PART_ID   LATEST_DATE   LOCATION
 C0001    09/04/2013     STORE
 C0002    09/05/2013     STORE
 C0003    08/01/2013      703
 C0004    09/10/2013     STORE
 C0005    08/02/2013      505
 C0006    08/02/2013      602
 C0007    09/12/2013     STORE
 C0008    09/13/2013     STORE
 C0009    08/03/2013      803

但我失败了。有人可以帮忙吗?非常感谢!

4

2 回答 2

1

好吧,以防万一您使用的是 MySQL(实际上,它也应该在 MSSQL 下运行!)然后您可以执行以下操作

SELECT pid,COALESCE(rdate,pdate) dat,COALESCE(rloc,ploc) lo FROM partlogout 
LEFT JOIN partreturn ON rid=pid AND rdate>pdate

看这里的一个小演示:SQLfiddle

编辑: 由于数据库显然在 MS-Access 下运行,因此命令应该是

SELECT pid,NZ(rdate,pdate) dat,NZ(rloc,ploc) lo FROM partlogout 
LEFT JOIN partreturn ON rid=pid AND rdate>pdate
于 2013-08-05T09:50:43.733 回答
0

我认为这应该有效:

SELECT 
  pl.PART_ID, 
  CASE WHEN ISNULL(RETURN_DATE,'1900-01-01') > DRAWN_DATE THEN RETURN_DATE ELSE DRAWN_DATE END AS 'Latest date',  
  CASE WHEN ISNULL(RETURN_DATE,'1900-01-01') > DRAWN_DATE THEN pr.LOCATION ELSE pl.LOCATION END AS 'Location'
FROM PART_LOGOUT pl 
LEFT JOIN PART_RETURN pr ON pl.PART_ID=pr.PART_ID
ORDER BY pl.PART_ID

您可能必须更改源表名称,因为我不确定它们是如何命名的。

于 2013-08-05T09:51:53.087 回答