如何编写查询以获得这样的输出?

How to write a query to get such output?

我想要 Pdate 列作为输出。 我有这三个属性:id、Bonus 和 Date。我必须获得日期列的输出,以便该列显示员工收到 20 欧元或超过 20 欧元的先前日期,对应于员工获得奖金的正常日期。看看下面的 table 来更深入地理解这个问题:

id Bonus    Date           my_output     Pdate(Required Output)
1   15  "2017-06-20"                    "2017-04-17"
1   10  "2017-05-22"                    "2017-04-17"
1   20  "2017-04-17"    "2017-04-17"    "2017-03-20"
1   20  "2017-03-20"    "2017-03-20"     NULL
2   15  "2017-02-20"                    "2017-01-28"
2   25  "2017-01-28"    "2017-01-28"     NULL

所以,正如您在第一行看到的那样,Bonus 是 15,因为我们希望 bonus 大于或等于 20,所以在“2017-04-17”,对于 id 1,bonus 是 20。因此,Pdate有那个日期。并且在第四行中,由于没有根据用户 1 的条件获得奖金的先前日期,因此 pdate 为空。

select id,Bonus_value as Bonus,
(case when Bonus_value>=0 then Bonus_date end) as date,
(case when Bonus_value>=20 then Bonus_date end) as my_output                                     
from Bonus                                       
group by id,Bonus_value,Bonus_date
order by id,Bonus_date desc

在此代码中,没有 pdate,因为我不知道如何获取该列。这是我想要的。我想到了使用 lead() window 函数,但我仍然不知道如何让它对应于日期列。

在标准 SQL 中,您可以使用 ignore nulls 选项:

select t.*,
       lag(case when bonus >= 20 then date end ignore nulls) over (partition by id order by date) as pdate
from t;

并非所有数据库都支持此选项,因此您也可以使用带有 window 子句的 max()

       max(case when bonus >= 20 then date end ignore nulls) over (partition by id order by date rows between unbounded preceding and 1 preceding) as pdate
from t;