Leetcode1173. 即时食物配送 I(简单)

题目
配送表: Delivery

+-----------------------------+---------+
| Column Name                 | Type    |
+-----------------------------+---------+
| delivery_id                 | int     |
| customer_id                 | int     |
| order_date                  | date    |
| customer_pref_delivery_date | date    |
+-----------------------------+---------+

delivery_id 是表的主键。
该表保存着顾客的食物配送信息,顾客在某个日期下了订单,并指定了一个期望的配送日期(和下单日期相同或者在那之后)。

如果顾客期望的配送日期和下单日期相同,则该订单称为 「即时订单」,否则称为「计划订单」。

写一条 SQL 查询语句获取即时订单所占的比例, 保留两位小数。

查询结果如下所示:

Delivery 表:

+-------------+-------------+------------+-----------------------------+
| delivery_id | customer_id | order_date | customer_pref_delivery_date |
+-------------+-------------+------------+-----------------------------+
| 1           | 1           | 2019-08-01 | 2019-08-02                  |
| 2           | 5           | 2019-08-02 | 2019-08-02                  |
| 3           | 1           | 2019-08-11 | 2019-08-11                  |
| 4           | 3           | 2019-08-24 | 2019-08-26                  |
| 5           | 4           | 2019-08-21 | 2019-08-22                  |
| 6           | 2           | 2019-08-11 | 2019-08-13                  |
+-------------+-------------+------------+-----------------------------+

Result 表:

+----------------------+
| immediate_percentage |
+----------------------+
| 33.33                |
+----------------------+

2 和 3 号订单为即时订单,其他的为计划订单。

解答
order_date 与 customer_pref_delivery_date 相同即为即时订单
计算即时订单的数量

select count(D1.delivery_id)
from Delivery as D1
where D1.order_date = D1.customer_pref_delivery_date

计算总订单的数量

select count(D2.delivery_id)
from Delivery as D2

两者相除保留小数即可

select round((select count(D1.delivery_id)
from Delivery as D1
where D1.order_date = D1.customer_pref_delivery_date) /
(select count(D2.delivery_id)
from Delivery as D2), 4
) * 100
as immediate_percentage

别的解答
条件选择

select round(
    sum(case when order_date=customer_pref_delivery_date then 1 else 0 end) /
    count(*)
   ,4)*100
as immediate_percentage
from Delivery
select round(
    sum(if(order_date=customer_pref_delivery_date, 1, 0)) /
    count(*)
   ,4)*100
as immediate_percentage
from Delivery

逻辑真值

select round(
    sum(order_date=customer_pref_delivery_date) /
    count(*)
    ,4)*100
as immediate_percentage
from Delivery
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容