从 MySql 切换到 Vertica,在 where 子句中聚合不起作用

Switching to Vertica from MySql, aggregate in where clause not working

最近我们从 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'

非常感谢任何帮助或指导!

在我的鼠标飞走并且我的显示器变成空白之前,我得到了这个错误:

ERROR: Correlated subquery with aggregate function COUNT is not supported

您将以这种方式使用子查询。您将使用 window 函数:

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';

备注:

  • 不要用单引号将列别名引起来。这是一个等待发生的错误。仅对字符串和日期常量使用单引号。
  • 您可以简化日期逻辑。使用 <<= 更好地捕捉特定日期发生的一切。