我有以下查询,可获取连接的多个表的计数:
select
count(distinct e.planningitemdata->>'receiverDuns') as supplierOrCustomer,
count(distinct e.planningitemdata->>'shipTo') as shipTo,
count(distinct e.planningitemdata->>'productId') as product,
count(distinct eo.orderlineid) as orderline,
count(distinct e.planningitemid) as planningitem
from
eventplanningitem e
join
eventorderline eo
on e.eventid = eo.eventid
join
orderline o
on eo.orderlineid = o.id
and o.deliveryrequesteddate between '2018-03-06' AND '2018-05-06'
where
e.eventId = '9f6d3d50-05ca-4441-a4e4-24de2b52de5b'
我想根据日期过滤器过滤“orderlineid”计数,但我的问题是,当我尝试将它应用于如上所示的连接时,它会显示所有其他计数的所有结果为 0。如果我尝试在末尾添加 where 子句,也会发生同样的事情。如果我将 orderline 表设为左外连接,我会得到与日期条件不匹配的 orderlines 的计数。
结果:
0;0;0;0;0
类似的版本会产生相同的结果:
select
count(distinct e.planningitemdata->>'receiverDuns') as supplierOrCustomer,
count(distinct e.planningitemdata->>'shipTo') as shipTo,
count(distinct e.planningitemdata->>'productId') as product,
count(distinct eo.orderlineid) as orderline,
count(distinct e.planningitemid) as planningitem
from
eventplanningitem e
join
eventorderline eo
on e.eventid = eo.eventid
join
orderline o
on eo.orderlineid = o.id
and o.deliveryrequesteddate between '2018-03-06' AND '2018-05-06'
where
e.eventId = '9f6d3d50-05ca-4441-a4e4-24de2b52de5b'
and (o.deliveryrequesteddate >='2018-03-06' and o.deliveryrequesteddate <= '2018-05-06')
如果我让 orderline 加入 a ,我会得到计数left outer join
,但它包括实际超出日期标准的 orderLine 记录,因此它也不正确。
我想避免将其分解为多个查询,但我想在走那条路线之前检查我是否遗漏了一些东西。
看起来你可以使用
COUNT(DISTINCT expression)
,所以我会尝试替换有了这个
NULL 值不计入
COUNT
,并且DISTINCT
仍应确保您只计算orderlineid
一次。@RDFozz 的另一种答案是使用
FILTER
:我认为它更直观一点,因为这是
FILTER
存在的确切原因,所以它的意图比使用CASE
.