【问题标题】:Switching to Vertica from MySql, aggregate in where clause not working从 MySql 切换到 Vertica,在 where 子句中聚合不起作用
【发布时间】:2017-03-15 08:47:44
【问题描述】:

最近我们从 MySQL 切换到 Vertica。我不知道如何在下面的查询中的 where 子句中重新创建

本质上,用户拥有汽车,汽车拥有零件。我想在一个时间范围内汇总汽车和汽车零件的数量,但仅限于拥有少于或等于 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 相关的子查询

【问题讨论】:

  • 这在 Vertica 中不起作用?
  • 它以什么方式“不起作用”?老鼠飞走了?显示器关了?让你消化不良?
  • 哈哈。对缺少信息表示歉意 - 我收到以下错误:“错误:不支持与聚合函数 COUNT 相关的子查询”
  • 请下次使用此信息更新问题,而不是提出新评论,请务必添加评论以说“谢谢@Nick.McDermaid”,但请保留问题中的重要内容
  • 我会为你添加错误

标签: sql vertica


【解决方案1】:

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

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

注意事项:

  • 不要将列别名括在单引号中。这是一个等待发生的错误。仅对字符串和日期常量使用单引号。
  • 您可以简化日期逻辑。使用&lt; 比&lt;= 更好地捕捉特定日期发生的所有事情。

【讨论】:

  • 这很好用!我看到分区成功了......我需要阅读更多内容才能完全理解它。这让我走上了正确的道路——我真的很感激!并且您的提示得到了适当的注意
猜你喜欢
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多