最近我们从MySQL切换到Vertica。我迷失了如何在下面的查询中的where子句内重新创建< = 30检查。这目前在Vertica中不起作用,但在MySQL中起作用。
基本上,用户拥有汽车,汽车拥有零件。我希望在一个时间范围内总计汽车和汽车零件的数量,但仅适用于小于或等于30辆汽车的用户。
select
count(distinct cr.id) as 'Cars',
count(distinct cp.id) as 'Car Parts'
from
users u
inner join
user_emails ue on u.id = ue.user_id
inner join
cars cr on cr.user_id = u.id
inner join
car_parts cp on cp.car_id = cr.id
where
(
select count(*) from cars where cars.user_id=u.id
) <=30
and
ue.is_real = true and ue.is_main = true
and
cr.created_at >= '2017-01-01 00:00:00' and cr.created_at <= '2017-02-17 23:59:59'
非常感谢任何帮助或指导!
在我的鼠标飞走并且我的显示器空白之前,我收到此错误:
错误:不支持具有聚合函数COUNT的相关子查询
答案 0 :(得分:0)
您将以这种方式使用子查询。您将使用窗口函数:
select count(distinct cr.id) as Cars,
count(distinct cp.id) as CarParts
from users u join
user_emails ue
on u.id = ue.user_id join
(select cr.*, count(*) over (partition by user_id) as cnt
from cars cr
) cr
on cr.user_id = u.id join
car_parts cp
on cp.car_id = cr.id
where cr.cnt <= 30 and
ue.is_real = true and ue.is_main = true
cr.created_at >= '2017-01-01' and
cr.created_at < '2017-02-18';
注意:
<
优于<=
来捕获特定日期发生的所有事情。