选择Statement Complicated data transformation

时间:2015-02-05 23:36:34

标签: sql netezza

好的我有2张桌子。

表A有一个给定客户端的事务列表,如下所示

ClientID Transaction  Start      Stop
1          1          2014-01-01 2014-01-25

表B是事件列表,如下所示:

ClientID Event StartE      StopE
1         1    2014-01-05 2014-01-08
1         2    2014-01-10 2014-01-12
1         3    2014-01-14 2014-01-16

我想将这些表“加入”以获得下表:

ClientID Transaction  EFF         ENDS
1          1          2014-01-01  2014-01-05
1          1          2014-01-05  2014-01-08
1          1          2014-01-08  2014-01-10
1          1          2014-01-10  2014-01-12
1          1          2014-01-12  2014-01-14
1          1          2014-01-14  2014-01-16
1          1          2014-01-16  2014-01-25

我已经提出了一些解决方案,但在某些情况下,这是我的代码失败的示例。我想尝试解决这个问题。

1 个答案:

答案 0 :(得分:1)

像这样的东西,未经过测试,所以不确定它是否有效。基本上我将所有日期联合到一列以及相应的事务编号,然后按日期排序并添加行号,然后将该结果集连接到自身以将每一行与后续行配对。

;WITH ordered AS (
    SELECT ROW_NUMBER OVER (ORDER BY [Date]) AS Row, ClientID, Transaction, [Date]
    FROM (
        SELECT ClientID, Transaction, StartE AS [Date]
        FROM B JOIN A ON StartE BETWEEN A.Start AND A.Stop

        UNION

        SELECT ClientID, Transaction, StopE AS [Date]
        FROM B JOIN A ON StopE BETWEEN A.Start AND A.Stop

        UNION

        SELECT ClientID, Transaction, Start AS [Date]
        FROM A

        UNION

        SELECT ClientID, Transaction, Start AS [Date]
        FROM A
    ) combineddates
)
SELECT o1.ClientID, o1.Transaction, o1.[Date] AS Start, o2.[Date] AS Stop
FROM ordered o1 JOIN ordered o2 ON o2.Row = o1.Row + 1