【问题标题】:Sum of 2 fetched columns in other column in Big query SQL大查询 SQL 中其他列中 2 个提取列的总和
【发布时间】:2016-11-24 15:17:33
【问题描述】:
select x,
count(case when i='abc' then 1 else null end) as ele1,
count(case when i='def' then 1 else null end) as ele2,
sum(ele1+ele2) as sum1 from (INNER QUERY)

当我使用 sum(ele1+ele2) 时,会抛出找不到 ele1 的错误。如何在不使用任何其他外部查询的情况下在同一查询中获取 sum1?

【问题讨论】:

标签: mysql sql google-bigquery calculated-columns


【解决方案1】:

您不能使用别名作为列名,但如果您担心的是冗长 - 在您的特定情况下,您可以编写如下内容,它易于阅读且足够简洁(对于 BigQuery Legacy SQL)

SELECT 
  SUM( i ='abc' ) AS ele1,
  SUM( i = 'def' ) AS ele2,
  SUM( i IN ('abc', 'def') ) AS sum1 
FROM (INNER QUERY)

【讨论】:

    【解决方案2】:

    您不能在选择中使用别名作为列名

    select x,
    count(case when i='abc' then 1 else null end) as ele1,
    count(case when i='def' then 1 else null end) as ele2,
    sum(  ( case when i='abc' then 1 else null end  ) +  
        ( case when i='def' then 1 else null end ) ) as sum1 
    from (INNER QUERY)
    

    【讨论】:

    • 我虽然也是这样,但没有其他方法,因为在这种情况下,我们必须再次应用会增加查询时间的条件
    • 也可以作为 count(case when i='abc' || i='def' then 1 else null end) as sum1 ...但是还有其他方法可以做到吗?
    • 我的答案是解决抛出错误,为此答案是正确的..为了更好的查询,有几种不同的解决方案,但这似乎是另一个问题.....就执行时间而言或者您提供的解决方案,in 解决方案或两种情况的解决方案非常相似.. 无论如何
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多