sql - 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'
我的计数不正确,并看到以下错误:
这是数据库架构:
解决方案
如果要统计租期超过 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 天。
推荐阅读
- multithreading - 为 JavaFX 任务实现暂停和恢复功能
- bash - 使用 bash 从 netcat 读取输出
- python - RuntimeError: cudaGetDevice() 失败。状态:无效参数
- mysql - 包含超过 562mb BLOB 的记录未插入 mysql
- android - 按下硬件音量按钮时如何在颤动应用程序中隐藏系统音量条?
- c# - 如何反序列化动态 Json 对象?
- pandas - 输入必须是数组、列表、元组或标量 pyproj
- python - Django 项目模板不存在
- c# - 具有自定义颜色的 DataTrigger
- python - Python 在 xml 中搜索