-1

希望你能帮忙。我们有一个包含两列 Customer_ID 和 Trip_Date 的表。客户在第一次访问以及在过去 30 天内未收到 15% 折扣优惠的每次访问时均可享受 15% 折扣。如何编写单个 SQL 查询来查找客户获得 15% 折扣的所有日期?

桌子看起来像这样

+-----+-------+----------+
| Customer_ID | date     |
+-----+-------+----------+
|          1  | 01-01-17 |
|          1  | 01-17-17 |
|          1  | 02-04-17 |
|          1  | 03-01-17 |
|          1  | 03-15-17 |
|          1  | 04-29-17 |
|          1  | 05-18-17 |
+-----+-------+----------+

所需的输出如下所示:

+-----+-------+----------+--------+----------+
| Customer_ID | date     | received_discount |
+-----+-------+----------+--------+----------+
|          1  | 01-01-17 |        1          |
|          1  | 01-17-17 |        0          |
|          1  | 02-04-17 |        1          |
|          1  | 03-01-17 |        0          |
|          1  | 03-15-17 |        1          |
|          1  | 04-29-17 |        1          |
|          1  | 05-18-17 |        0          |
+-----+-------+----------+--------+----------+

我们正在 Netezza 中进行这项工作。我想不出只使用窗口函数,只使用递归和循环的方法。我错过了一些聪明的把戏吗?

提前致谢, GF

4

1 回答 1

0

You didn't tell us what your backend is, nor you gave some sample data and expected output nor you gave a sensible data schema :( This is an example based on guess of schema using postgreSQL as backend (would be too messy as a comment): (I think you have Customer_Id, Trip_Date and LocationId in trips table?)

select * from trips t1
where not exists (
  select * from trips t2 
  where t1.Customer_id = t2.Customer_id and
  t1.Trip_Date > t2.Trip_Date 
  and t1.Trip_date - t2.Trip_Date < 30
);
于 2018-12-05T19:19:05.577 回答