简体   繁体   English

如果出现新客户,如何从给定客户最接近的旧记录中获取日期

[英]How to get date from closest old record for the given customer if a new one appears

I am dealing with policy records table inside Google BigQuery.我正在处理 Google BigQuery 中的策略记录表。 My table has three columns: INDVDL_ID, POLICY_ID and CNV_DT.我的表有三列:INDVDL_ID、POLICY_ID 和 CNV_DT。 Every unique client is identified with INDVDL_ID and may have one or more records in the table depending on how many policies he has.每个唯一的客户端都用 INDVDL_ID 标识,并且可能在表中具有一条或多条记录,具体取决于他拥有多少策略。 Each policy has it's id (POLICY_ID) and the date that it was bought (CNV_DT).每份保单都有其 ID (POLICY_ID) 和购买日期 (CNV_DT)。 So the code for pulling the data that I am using looks like that:因此,用于提取我正在使用的数据的代码如下所示:

SELECT INDVDL_ID, POLICY_ID, CNV_DT
FROM `Policy_table.TP_Policies.policy_20191023

What I have:我有的:

 <table><tbody><tr><th>INDVDL_ID</th><th>POLICY_ID</th><th>CNV_DT</th></tr><tr><td>1</td><td>1</td><td>2008-01-01</td></tr><tr><td>1</td><td>2</td><td>2008-04-31</td></tr><tr><td>1</td><td>3</td><td>2008-12-23</td></tr><tr><td>3</td><td>4</td><td>2009-08-19</td></tr><tr><td>2</td><td>5</td><td>2010-06-12</td></tr><tr><td>2</td><td>6</td><td>2011-11-12</td></tr></tbody></table>

What I would like to pull is table, where for every additional policy that customer has bought I can have a CNV_DT of his prior purchase.我想拉的是表格,对于客户购买的每一项额外保单,我都可以拥有他之前购买的 CNV_DT。

What I would like to have:我想拥有的:

 <table><tbody><tr><th>INDVDL_ID</th><th>POLICY_ID</th><th>CNV_DT</th><th>PRIOR_CNV_DT</th></tr><tr><td>1</td><td>1</td><td>2008-01-01</td><td> </td></tr><tr><td>1</td><td>2</td><td>2008-04-31</td><td>2008-01-01</td></tr><tr><td>1</td><td>3</td><td>2008-12-23</td><td>2008-04-31</td></tr><tr><td>3</td><td>4</td><td>2009-08-19</td><td> </td></tr><tr><td>2</td><td>5</td><td>2010-06-12</td><td> </td></tr><tr><td>2</td><td>6</td><td>2011-11-12</td><td>2010-06-12</td></tr></tbody></table>

You seem to want lag() :你似乎想要lag()

SELECT INDVDL_ID, POLICY_ID, CNV_DT,
       LAG(CNV_DT) OVER (PARTITION BY INDVDL_ID ORDER BY CNV_DT) as PRIOR_CNV_DT
FROM `Policy_table.TP_Policies.policy_20191023;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM