Big查询SQL中其他列中的2个读取列的总和

时间:2016-07-21 07:08:59

标签: mysql sql google-bigquery calculated-columns

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?

2 个答案:

答案 0 :(得分: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)

答案 1 :(得分: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)