首页 > 解决方案 > sql查询查找租赁天数大于等于10天的客户

问题描述

我想找到每个租用天数大于 10 天的客户。我的解决方案没有给我任何语法错误,但它给出的客户总数不正确。这是我的解决方案:

with rental_history as (
   select
      customer_id
      ,rental_date
      ,return_date
      ,rental_date + interval '10 day' as ban_date
      ,coalesce(return_date, now())-rental_date as days_out
   from rental
)
select count(*) as number_of_lost_rentals
from rental_history where days_out >= interval '10 day'

我的计数不正确,并看到以下错误:

在此处输入图像描述

这是数据库架构:

在此处输入图像描述

标签: sqlpostgresql

解决方案


如果要统计租期超过 10 天的客户,则:

select count(distinct customer_id)
from rental
where rental_date <= coalesce(return_date, current_date) - interval 10 'day';

如果你想计算一个客户所有租金的天数——这就是我对这个问题的解释——那么你需要聚合:

select count(*)
from (select customer_id,
             sum( (coalesce(return_date, current_date) - rental_date) )::int as num_days
      from rental r
      group by customer_id
     ) c
where num_days >= 10;

注意:从您的问题中也不清楚,如果有人在 2020 年 9 月 1 日租房并在 2020 年 9 月 1 日返回,那么算作 1 天还是 2 天。


推荐阅读