如果在另一个时间戳之后发生时间戳,请选择时间戳的最小差异

时间:2014-08-14 18:38:38

标签: sql teradata

我的表格显示customer_idproduct_idbrowse_datepurchase_date以及浏览和购买日期之间的差异。它看起来像这样。

id  pID  b_Date     p_Date       Diff
1   001  7/20/2014  7/20/2014    0
1   001  7/20/2014  7/20/2014    0
1   002  7/20/2014  7/20/2014    0
2   001  7/20/2014  7/20/2014    0
2   001  7/20/2014  8/01/2014    -12
2   002  7/25/2014  8/01/2014    -8
2   002  7/26/2014  8/01/2014    -7
2   002  7/28/2014  8/01/2014    -5
2   002  7/28/2014  8/01/2014    -5

我试图找到客户在购买前开始浏览特定产品的高级天数。

但是,在客户2的情况下,他做了两次购买。现在他在2014年7月20日进行的浏览不应被视为他在2014年8月1日购买的浏览量,因为这与7月20日的购买有关。

我想知道如何为上次购买后浏览发生的每个客户获取MIN Diff。另外,我无法在查询中使用pID(产品ID)。

我正在使用teradata 13.1

1 个答案:

答案 0 :(得分:0)

您的问题对我来说有点模糊,但我认为您要求客户diff为特定购买设置最低id,而不管pID。以下是完成该操作的后续查询和后续查询。

以下是基于您提供的数据集的结果:

id  Max_b_Date  p_Date      Min_Diff
1   2014-07-20  2014-07-20      0
2   2014-07-20  2014-07-20      0
2   2014-07-28  2014-08-01      -5

以及我用于在Teradata 13.1中重新创建问题的代码

CREATE MULTISET TABLE danf.table1
    (
    id INTEGER NOT NULL,
    pID VARCHAR(50) CHARACTER SET LATIN NOT CASESPECIFIC,
    b_Date DATE FORMAT 'MM/DD/YYYY' ,
    p_Date DATE FORMAT 'MM/DD/YYYY' ,
    Diff INTEGER 
    )
PRIMARY INDEX ( id );

INSERT INTO danf.table1 (id, pID, b_Date, p_Date, Diff) VALUES ( 1, '001', CAST('07/20/2014' AS DATE FORMAT 'MM/DD/YYYY'), CAST('07/20/2014' AS DATE FORMAT 'MM/DD/YYYY'), 0 );
INSERT INTO danf.table1 (id, pID, b_Date, p_Date, Diff) VALUES ( 1, '001', CAST('07/20/2014' AS DATE FORMAT 'MM/DD/YYYY'), CAST('07/20/2014' AS DATE FORMAT 'MM/DD/YYYY'), 0 );
INSERT INTO danf.table1 (id, pID, b_Date, p_Date, Diff) VALUES ( 1, '002', CAST('07/20/2014' AS DATE FORMAT 'MM/DD/YYYY'), CAST('07/20/2014' AS DATE FORMAT 'MM/DD/YYYY'), 0 );
INSERT INTO danf.table1 (id, pID, b_Date, p_Date, Diff) VALUES ( 2, '001', CAST('07/20/2014' AS DATE FORMAT 'MM/DD/YYYY'), CAST('07/20/2014' AS DATE FORMAT 'MM/DD/YYYY'), 0 );
INSERT INTO danf.table1 (id, pID, b_Date, p_Date, Diff) VALUES ( 2, '001', CAST('07/20/2014' AS DATE FORMAT 'MM/DD/YYYY'), CAST('08/01/2014' AS DATE FORMAT 'MM/DD/YYYY'), -12 );
INSERT INTO danf.table1 (id, pID, b_Date, p_Date, Diff) VALUES ( 2, '002', CAST('07/25/2014' AS DATE FORMAT 'MM/DD/YYYY'), CAST('08/01/2014' AS DATE FORMAT 'MM/DD/YYYY'), -8 );
INSERT INTO danf.table1 (id, pID, b_Date, p_Date, Diff) VALUES ( 2, '002', CAST('07/26/2014' AS DATE FORMAT 'MM/DD/YYYY'), CAST('08/01/2014' AS DATE FORMAT 'MM/DD/YYYY'), -7 );
INSERT INTO danf.table1 (id, pID, b_Date, p_Date, Diff) VALUES ( 2, '002', CAST('07/28/2014' AS DATE FORMAT 'MM/DD/YYYY'), CAST('08/01/2014' AS DATE FORMAT 'MM/DD/YYYY'), -5 );
INSERT INTO danf.table1 (id, pID, b_Date, p_Date, Diff) VALUES ( 2, '002', CAST('07/28/2014' AS DATE FORMAT 'MM/DD/YYYY'), CAST('08/01/2014' AS DATE FORMAT 'MM/DD/YYYY'), -5 );

SELECT 
    t1.id
    ,MAX(b_Date) AS Max_b_Date
    ,t1.p_Date
    ,MAX(t1.Diff) AS Min_Diff
FROM danf.table1 t1
GROUP BY 
    t1.id, 
    t1.p_Date;