这条 sql 是在写不出来了😔,下面是简化的表结构和条件。
| user_id |
username |
| 1 |
张三 |
| 2 |
李四 |
| 3 |
王五 |
| order_id |
user_id |
order_name |
create_time |
is_active |
shift |
| 1 |
1 |
001 |
2020-01-01 12:12:12 |
0 |
day |
| 2 |
1 |
001 |
2020-01-01 23:00:00 |
1 |
night |
| 3 |
1 |
002 |
2020-01-01 12:12:12 |
1 |
day |
| 4 |
1 |
002 |
2020-01-01 23:00:00 |
0 |
night |
| class_id |
order_id |
sw_class |
|
| 1 |
1 |
采购 |
|
| 2 |
2 |
消费 |
|
| 3 |
2 |
消费 |
|
| 4 |
3 |
消费 |
|
| 5 |
4 |
消费 |
|
效果:
查询姓名为张三的订单
并根据订单的创建日期,班次(night,day),是否激活 is_active,作为一组条件
统计订单所属类别(表三) sw_class 的数量
例如 张三 在 2020-01-01 这一天,有订单
is_activce = 1 的 且 shift = night 的 订单 为 order_id = 2
那么类别有 class_id (2,3),消费消费 ,
那么就有一条记录:
| username |
is_active |
shift |
date |
sw_采购 |
sw_消费 |
sw_采购占订单总数比例 |
sw_消费占订单总数比例 |
| 张三 |
1 |
night |
2020-01-01 |
0 |
2 |
2/2 |
0/2 |
结果例如:
| username |
is_active |
shift |
date |
sw_采购 |
sw_消费 |
sw_采购占订单总数比例 |
sw_消费占订单总数比例 |
| 张三 |
0 |
night |
2020-01-01 |
0 |
1 |
1/1 |
0/1 |
| 张三 |
1 |
night |
2020-01-01 |
0 |
2 |
2/2 |
0/2 |
| 张三 |
0 |
day |
2020-01-01 |
1 |
0 |
1/1 |
0/1 |
| 张三 |
1 |
day |
2020-01-01 |
0 |
1 |
0/1 |
1/1 |