首先想到的方式 直接限制
select
a.projectid
,DIM.projectname
,DIM.areaname
,to_char(a.msgtimestamp,'yyyyMMdd')
--,count(a.id)
,count(1) --客户询问数目
,count(b.id) --24小时回复数目
from ods.xk_c_user_broker_chat_records a --来询问人记录
inner join ods.xk_a_broker_user a1
on a.from_account=a1.id
left join ODS.XK_B_PROJECT DIM
ON A.projectid = DIM.id
left join ods.xk_c_user_broker_chat_records b
on a.conversationid=b.conversationid
and b.msgtimestamp>=a.msgtimestamp
and b.msgtimestamp<=a.msgtimestamp + INTERVAL '24' HOUR
and b.DataType not IN ('system', 'timeoutMsg' )
-- inner join ods.xk_b_account c
-- on c.id=b.to_account
-- and c.status=1
-- and c.isdel=0
where a.projectid='01802085-5D65-4348-8088-550A4EFDC2EB'
and to_char(a.msgtimestamp,'yyyyMMdd')='20210831'
group by
a.projectid
,DIM.projectname
,DIM.areaname
,to_char(a.msgtimestamp,'yyyyMMdd')
order by to_char(a.msgtimestamp,'yyyyMMdd')
这段代码的想法是用C限制B表。但是实际上会把A也限制掉。因为A会先和B组成临时表然后C来限制这个临时表,C就对A有了限制作用
应该
with tmp as (
select
a.projectid
,a.msgtimestamp msgtimestamp
,DIM.projectname
,DIM.areaname
,a.conversationid
,a.id
from ods.xk_c_user_broker_chat_records a --来询问人记录
inner join ods.xk_a_broker_user a1
on a.from_account=a1.id
left join ODS.XK_B_PROJECT DIM
ON A.projectid = DIM.id
),
tmp1 as(
select
b.conversationid
,b.id
,b.msgtimestamp msgtimestamp
from ods.xk_c_user_broker_chat_records b
inner join ods.xk_b_account c
on c.id=b.to_account
and c.status=1
and c.isdel=0
and b.DataType not IN ('system','timeoutMsg')
where b.projectid='01802085-5D65-4348-8088-550A4EFDC2EB'
and to_char(b.msgtimestamp,'yyyyMMdd') in ('20210831','20210901')
)
select
a.projectid
,a.projectname
,a.areaname
,to_char(a.msgtimestamp,'yyyyMMdd') msgtimestamp
--,count(a.id)
,count(1) --客户询问数目
,count(b.id) --24小时回复数目
from tmp a
left join(
select
bb.conversationid
,bb.id
,bb.msgtimestamp
from tmp aa
inner join tmp1 bb
on aa.conversationid=bb.conversationid
where bb.msgtimestamp>=aa.msgtimestamp
and bb.msgtimestamp<=aa.msgtimestamp + INTERVAL '24' HOUR
) b
on a.conversationid=b.conversationid
where a.projectid='01802085-5D65-4348-8088-550A4EFDC2EB'
and to_char(a.msgtimestamp,'yyyyMMdd')='20210831'
group by
a.projectid
,a.projectname
,a.areaname
,to_char(a.msgtimestamp,'yyyyMMdd')