使用GROUP BY的Bigquery错误,使用ALIAS的Bigquery错误

时间:2018-07-20 08:36:32

标签: google-bigquery

我注意到bigquery标准sql中出现一个奇怪的错误。 我有一张桌子:

SELECT * FROM ds.sod;
| id | name  |
|----+-------|
| 1  | tom   |
| 2  | dick  |
| 3  | harry |

所以,如果我按表达式分组,那么它会起作用

SELECT MOD(id,2) AS oddeven, COUNT(1) AS cnt
FROM ds.sod GROUP BY MOD(id,2)
| oddeven | cnt |
+---------+-----+
|       1 |   2 |
|       0 |   1 |

但是,如果我添加HAVING子句,它将失败。

SELECT MOD(id,2) AS oddeven, COUNT(1) AS cnt
FROM ds.sod GROUP BY MOD(id,2) HAVING COUNT(1) > 0
ERROR: SELECT list expression references column id which is neither grouped nor aggregated

现在奇怪的是,如果我不对列进行别名

SELECT MOD(id,2), COUNT(1) AS cnt
FROM ds.sod GROUP BY MOD(id,2) HAVING COUNT(1) > 0
| f0_ | cnt |
+-----+-----+
|   1 |   2 |
|   0 |   1 |

如果我不使用函数,它也可以使用别名

SELECT id AS oddeven, COUNT(1) AS cnt
FROM ds.sod GROUP BY id HAVING COUNT(1) > 1
| oddeven | cnt |
+---------+-----+
|       3 |   1 |
|       2 |   1 |
|       1 |   1 |

我做错什么了吗?还是这是bigquery标准SQL解析中的错误?

编辑:刚刚指出,如果我按别名分组(那是我从未做过的事情,因为在oracle 7中无法正常工作),它确实可以工作

SELECT MOD(id,2) AS oddeven, COUNT(1) AS cnt
FROM ds.sod GROUP BY oddeven HAVING COUNT(1) > 0
| oddeven | cnt |
+---------+-----+
|       1 |   2 |
|       0 |   1 |

1 个答案:

答案 0 :(得分:0)

或者您可以使用列位置

with

sample_data as (
    select
        *
    from
        unnest(
            array[
                struct(1 as id, 'tom' as name),
                struct(2, 'dick'),
                struct(3, 'harry')
            ]
        )
)

select
    mod(id, 2) as oddeven,
    count(*) as cnt
from
    sample_data
group by
    1
having
    count(*) > 0