如何有条件地获取SELECT中的上一行?

时间:2017-04-26 05:37:49

标签: sql sql-server database

this question中,有几种方法可以访问SELECT语句中的上一行。但是,我无法弄清楚如何有条件地做到这一点。

例如,假设我们有一个Transactions表:

customer_id  purchase_date  merchandise_type  merchandise_name
-----------------------------------------------------------------
1            12 Apr         Rice              Jasmine
1            18 Apr         Rice              Basmati 
1            19 Apr         Rice              Long-Grain
3            13 Apr         Rice              Jasmine

我想知道顾客在购买商品后多久改变了主意,预计产量是:

customer_id  merchandise_name  days
------------------------------------
1            Jasmine           6
1            Basmati           1

顾客1买了茉莉香米,然后6天后买了巴斯马蒂米饭,所以"天"在第一条记录中是6.以下代码能够执行此操作:

select customer_id, merchandise_name,
       purchase_date - LAG(purchase_date) over (order by purchase_date) as days
from Transactions

然而,当有其他类型的商品时它不会起作用:

customer_id  purchase_date  merchandise_type  merchandise_name
-----------------------------------------------------------------
1            12 Apr         Rice              Jasmine
1            13 Apr         Cafe              Maxwell
1            18 Apr         Rice              Basmati 
1            19 Apr         Rice              Long-grain
1            19 Apr         Cafe              Nescafe
3            13 Apr         Rice              Jasmine
3            14 Apr         Cafe              Nescafe

是否有可能获得某个条件的前一行?类似的东西:

...
order by purchase_date
where LAG(merchandise_type) = merchandise_type

1 个答案:

答案 0 :(得分:2)

您正在寻找的是OVER函数中的PARTITION BY子句:

select customer_id, merchandise_name,
       purchase_date - 
         LAG(purchase_date) over (partition by customer_id, merchandise_type
                                  order by purchase_date) as days
from Transactions

如果没有此子句,您将获得purchase_date的任何先前值。