2015-03-31 37 views
0

假設我銷售跨越時間間隔(天,月,甚至年)的服務。我有一個產品表,其中列出了每個產品,以及Customer_IDService_startService_end日期。如何分別在每個組的記錄之間創建笛卡爾產品?

現在我想列出每個客戶內的所有配對組合(Service_start,Service_end);例如(由CUSTOMER_ID排序表)

Lp Service_start Service_end Customer_ID 
-------------------------------------------- 
1  2-Feb-2014 8-Aug-2014 1 
2  5-May-2014 20-Dec-2014 1 
3  7-Jul-2014 9-Sep-2014 1 
4 13-Jan-2014 13-Jan-2015 2 
..  ...    ...  ... 

我想變成

Lp Service_start Service_end Customer_ID 
-------------------------------------------- 
1  2-Feb-2014 8-Aug-2014 1 
2  2-Feb-2014 20-Dec-2014 1 
3  2-Feb-2014 9-Sep-2014 1 
4  5-May-2014 8-Aug-2014 1 
5  5-May-2014 20-Dec-2014 1 
6  5-May-2014 9-Sep-2014 1 
7 13-Jan-2014 8-Aug-2014 1 
8 13-Jan-2014 20-Dec-2014 1 
9 13-Jan-2014 9-Sep-2014 1 
10 13-Jan-2014 13-Jan-2015 2 
...  ...    ... ... 

表是足夠大,它不適合到內存中。

SQL如何實現?還是SAS?

回答

2

您可以在SAS和SQL中執行此操作。下面是SQL的想法:

select ss.service_start, se.service_end, ss.customer_id 
from (select distinct customer_id, service_start from table) ss join 
    (select distinct customer_id service_end from table) se 
    on ss.customer_id = se.customer_id; 

這是SAS proc sql兼容。

在SQL的大多數方言中,您可以使用row_number() over (order by customer_id, service_start, service_end)添加lp列。在SAS中,您可以使用monotonic()proc sql之後的數據步。