我有必须找到产品的开始日期和结束日期的情况
我有一张如下表格,
Product Country Attribute_1 Attribute_2 Attribute_3 Transaction_date
ABC US Color Green Small 20130101
ABC US Color Green Small 20130102
ABC US Color Green Small 20130103
ABC US Color Green Small 20130104
ABC US Color Green Small 20130105
ABC US Color Red Big 20130201
ABC US Color Red Big 20130202
ABC US Color Red Big 20130203
ABC US Color Red Big 20130204
ABC US Color Red Big 20130205
ABC US Color Green Small 20130301
ABC US Color Green Small 20130302
ABC US Color Green Small 20130303
ABC US Color Green Small 20140101
输出应该是,
Product Country Attribute_1 Attribute_2 Attribute_3 Start_Date End_Date
ABC US Color Green Small 20130101 20130201
ABC US Color Red Big 20130201 20130301
ABC US Color Green Small 20130301 99999999
此处唯一的密钥是PRODUCT + COUNTRY
我尝试了如下所示的MIN,MAX和FIRST_VALUE以及LAST_VALUE,但无法获得所需的结果。
FIRST_VALUE(Transaction_date) OVER (PARTITION BY PRODUCT, COUNTRY OVER Attrubute1, Attribute_2, Attribute_3 ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
试过Min,Max和Groupby,它没有给出理想的结果。输出是
Product Country Attribute_1 Attribute_2 Attribute_3 Start_Date End_Date
ABC US Color Green Small 20130101 20140101
ABC US Color Red Big 20130201 20130205
在这种情况下,如果我将日期传递给20130204,我会得到两条记录。理想情况下,我应该只得到第二条记录。
有人可以帮助我获得理想的结果。
答案 0 :(得分:0)
使用
lag(coalesce(Attribute_1,'')||'|'
||coalesce(Attribute_1,'')||'|'
||coalesce(Attribute_1,'')) as la
over (partition by Product, Country order by Transaction_date)
获取前一行的属性。
过滤掉当前行和上一行具有相同属性的所有行。这将为您提供所需输出中的3行。
从这一点来看,构建查询的其余部分应该是微不足道的。