我有两张桌子,我们称之为桌子A& B: -
表A如下所示:
A.Num1 | A.Num2 | A.Date
12345 | 38170 | 28/05/2013
12345 | 38170 | 29/05/2013
12345 | 38170 | 31/05/2013
12345 | 38170 | 01/06/2013
12345 | 38170 | 03/06/2013
12345 | 38170 | 04/06/2013
12345 | 38170 | 04/06/2013
12345 | 38170 | 07/06/2013
表2(B)看起来像这样:
B.Num1 | B.Num2 | B.Status | B.Date
12345 | 38170 | New | 28/05/2013
12345 | 38170 | Closed | 31/05/2013
12345 | 38170 | Reopened | 04/06/2013
我需要一个像这样的表作为输出 - 它应该基本上包含来自表A的所有行+来自表B的状态
Num1 | Num2 | Status | Date
12345 | 38170 | New | 28/05/2013
12345 | 38170 | New | 29/05/2013
12345 | 38170 | Closed | 31/05/2013
12345 | 38170 | Closed | 01/06/2013
12345 | 38170 | Closed | 03/06/2013
12345 | 38170 | Reopened | 04/06/2013
12345 | 38170 | Reopened | 04/06/2013
12345 | 38170 | Reopened | 07/06/2013
另外,最好通过简单的SQL语句,而不是程序。
提前致谢。请对任何澄清发表评论
Indru
当表B中的两行状态发生变化但在同一日期时,我在连接中得到的值不一致。
举个例子:
我有两张桌子,比如A& B.它们是非常大的表格,它们记录了某些信息。表A每隔几天扫描一次数据但缺少状态列的文档 如果有更改,则表B获取具有状态列的新条目。 我需要匹配这两个并导出表A中与B对应的每个条目的状态。
Id | Num1 | Num2 | CreatedOn | Status
100 | 12345 | 38170 | 28/05/2013 | New
150 | 12345 | 38170 | 28/05/2013 | Closed
200 | 12345 | 38170 | 31/05/2013 | Reopened
250 | 12345 | 38170 | 04/06/2013 | Closed
Id | Num1 | Num2 | CreatedOn
55 | 12345 | 38170 | 28/05/2013
99 | 12345 | 38170 | 30/05/2013
145 | 12345 | 38170 | 31/05/2013
192 | 12345 | 38170 | 31/05/2013
223 | 12345 | 38170 | 04/06/2013
Id | Num1 | Num2 | CreatedOn | Status
55 | 11552 | 38170 | 28/05/2013 | New
99 | 11552 | 38170 | 30/05/2013 | Closed
145 | 11552 | 38170 | 31/05/2013 | Reopened
192 | 11552 | 38170 | 31/05/2013 | Reopened
223 | 11552 | 38170 | 04/06/2013 | Closed
相反,我得到:(使用Jeffrey Kamp的回复)
Id | Num1 | Num2 | CreatedOn | Status
55 | 11552 | 38170 | 28/05/2013 | Closed
99 | 11552 | 38170 | 30/05/2013 | Closed
145 | 11552 | 38170 | 31/05/2013 | Reopened
192 | 11552 | 38170 | 31/05/2013 | Reopened
223 | 11552 | 38170 | 04/06/2013 | Closed
这个:(使用回复2 - Mark Bannister)
Id | Num1 | Num2 | CreatedOn | Status
55 | 11552 | 38170 | 28/05/2013 | New
99 | 11552 | 38170 | 30/05/2013 | New
145 | 11552 | 38170 | 31/05/2013 | Reopened
192 | 11552 | 38170 | 31/05/2013 | Reopened
223 | 11552 | 38170 | 04/06/2013 | Closed
显然,记录Id-55可以是New或Closed,因为表B中同一天(28/05/13)有两个条目。但逻辑是它来自New - >已关闭 - >重新开放 有没有办法做到这一点?
答案 0 :(得分:4)
对于初学者来说简单:
SELECT A.Num1
,A.Num2
,NVL(
(SELECT DISTINCT
FIRST_VALUE(B.Status)
OVER (ORDER BY B.Date DESC)
FROM B
WHERE B.Num1 = A.Num1
AND B.Num2 = A.Num2
AND B.Date <= A.Date
),'New') AS Status
,A.Date
FROM A;
可能有一种更好的方法可以更快地运作。
答案 1 :(得分:4)
尝试:
select a.Num1, a.Num2, a."Date", b.Status
from TableA a
join (select TableB.*,
lead("Date",1) over (partition by Num1, Num2
order by "Date") NextDate
from TableB) b
on a.Num1 = b.Num1 and
a.Num2 = b.Num2 and
a."Date" >= b."Date" and
a."Date" < coalesce(b.NextDate,a."Date"+1)
SQLFiddle here。