我想创建一个接受2023年所有日期的查询(在本例中,我使用Order表作为辅助表,它用于订单注册以获得日期,它始终具有每天的日期),然后使用所有客户ID提供Left Join,您每天有多少订单,如果您当天没有任何订单,则返回0.我以客户端id 10552为例,但还会有其他几个.
我只使用了一个表,即order,它包含下了订单,我将在其中使用它来获取一年中的日期以及按客户ID计算的订货量.
当我执行select * from order时,来自order表的一些信息的示例:
created_at | order_status_id | client_id |
---|---|---|
2018-04-05 22:19:29.000 | 3 | 10,282 |
2018-04-22 23:47:36.000 | 3 | 2 |
2018-04-25 23:42:22.000 | 3 | 11 |
2018-04-06 19:54:33.000 | 4 | 2 |
2018-04-09 12:11:06.000 | 3 | 2 |
我正在try 使用以下查询来执行我想要的操作:
with Datas as (
select distinct
CAST(o.created_at AS DATE) datas
from platform_bs."order" o
where date_format(o.created_at, '%Y') = '2023'
order by 1
),-- here I put it to list all the dates from 2023 until now
count_orders_client as(
SELECT
datas,
od.client_id,
nullif(count(od.id),0) as count
from Datas as dt
left join platform_bs."order" od ON dt.datas = CAST(od.created_at AS DATE)
group by 1,2
order by 1,2
)-- here I do a left join to get the dates, client id and a count and where should I do it if there were no records on the day, it would return 0
select * from count_orders_client where client_id = 10552
我想让它退还这个:
datas | client_id | count |
---|---|---|
2023-01-01 | 10552 | 1 |
2023-01-02 | 10552 | 1 |
2023-01-03 | 10552 | 0 |
2023-01-04 | 10552 | 0 |
2023-01-05 | 10552 | 0 |
2023-01-06 | 10552 | 0 |
2023-01-07 | 10,552 | 1 |
2023-01-08 | 10,552 | 2 |
2023-01-09 | 10552 | 0 |
2023-01-10 | 10552 | 0 |
2023-01-11 | 10552 | 0 |
2023-01-12 | 10552 | 0 |
但当运行时,它返回如下所示:
datas | client_id | count |
---|---|---|
2023-01-01 | 10,552 | 1 |
2023-01-02 | 10,552 | 1 |
2023-01-07 | 10,552 | 1 |
2023-01-08 | 10,552 | 2 |
2023-01-13 | 10,552 | 1 |
2023-01-23 | 10,552 | 1 |
2023-02-27 | 10,552 | 1 |
我没有让左连接的一部分将2023年的日期与Order表连接起来,以返回值0.我该怎么办?
编辑1:正在使用AWS雅典娜