【问题标题】:Bigquery error with GROUP BY and HAVING with ALIASGROUP BY 的 Bigquery 错误和 ALIAS 的 HAVING
【发布时间】:2018-12-28 12:33:06
【问题描述】:

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

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

所以,如果我按 exporession 分组,它会起作用

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 |

【问题讨论】:

  • 我猜这是一个错误!也许 BigQuery 团队的某个人会看到这篇文章并澄清一下

标签: google-bigquery


【解决方案1】:

或者你可以使用列位置

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 2016-07-23
    • 2016-11-12
    • 1970-01-01
    相关资源
    最近更新 更多