【问题标题】:SQL: Syntax Error after Having (Select ...) tableSQL:拥有(选择...)表后的语法错误
【发布时间】:2021-09-01 21:33:39
【问题描述】:

问题是提取关于花费最多(作为客户在其整个生命周期中)total_amt_usd 的客户的信息,并计算他们在每个渠道中拥有的 web_events。

我正在尝试从原始表创建一个额外的表,并且需要两个表来提取信息。但是,我不断收到语法错误,无法继续进行。

SELECT t1.acc, COUNT(w.channel) total,
sum(case when w.channel = 'direct' then 1 else 0 end) direct,
sum(case when w.channel = 'adwords' then 1 else 0 end) adwords,
sum(case when w.channel = 'banner' then 1 else 0 end) banner,
sum(case when w.channel = 'facebook' then 1 else 0 end) facebook,
sum(case when w.channel = 'organinc' then 1 else 0 end) organic,
sum(case when w.channel = 'twitter' then 1 else 0 end) twitter
FROM web_events w
HAVING (
    SELECT o.account_id acc, SUM(o.total_amt_usd) total
    FROM orders o
    GROUP BY 1
    ORDER BY 2 DESC
    LIMIT 1
) t1
GROUP BY t1.acc

在Having 之后和group by 之前,表末尾的't1' 附近有语法错误。

【问题讨论】:

  • (1) 使用您正在使用的数据库进行标记。 (2) 解释你想要完成什么。您的 having 子句对我来说也没有意义。 (3)t1是什么?
  • 只有 FROM 列表中的子查询才能被赋予别名。
  • 你能用语言描述你对查询的意图吗?
  • @jarlh:当然还有 - JOIN 子句中的那些 - 如果有的话
  • @marc_s,JOIN 子句是 FROM 子句的一部分。

标签: sql create-table having having-clause


【解决方案1】:

如果您只想包含带有订单的帐户——我最好猜测你可能会尝试什么——我建议使用带有existswhere 子句:

SELECT w.account_id, COUNT(w.channel) total,
       sum(case when w.channel = 'direct' then 1 else 0 end) as direct,
       sum(case when w.channel = 'adwords' then 1 else 0 end) as adwords,
       sum(case when w.channel = 'banner' then 1 else 0 end) as banner,
       sum(case when w.channel = 'facebook' then 1 else 0 end) as facebook,
       sum(case when w.channel = 'organinc' then 1 else 0 end) as organic,
       sum(case when w.channel = 'twitter' then 1 else 0 end) as twitter
FROM web_events w
WHERE EXISTS (SELECT 1
              FROM orders o
              WHERE o.account_id = w.account_id
             )
GROUP BY w.account_id;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 1970-01-01
    相关资源
    最近更新 更多