繁体   English   中英

为什么相同的查询结果在 BigQuery 编辑器和 sqlalchemy 上不同?

[英]Why same query results are different on BigQuery editor and sqlalchemy?

我的大查询查询是:

SELECT d.type AS `error_type`, count('d.type') AS `count` 
FROM `table_android`, unnest(`table_android`.`exceptions`) AS `d` 
WHERE `table_android`.`event_timestamp` BETWEEN '2022-12-15' AND '2022-12-20' GROUP BY `error_type` ORDER BY `count` desc;

此查询在 bigquery 编辑器中运行良好。 但是与 sqlalchemy 相同版本的查询我无法得到相同的结果。

sqlalchemy查询:

sa.select(
    sa.literal_column("d.type").label("Error_Type"),
    sa.func.count("Error_Type").label("count"),
)
.select_from(sa.func.unnest(table_android.c.exceptions).alias("d"))
.group_by("Error_Type")
.order_by(desc("count"))
.where(table_android.c.event_timestamp.between('2022-12-15', '2022-12-20'))
.cte("main_table")

正确结果: 正确的结果

错误结果: 结果错误

我正在使用 python-bigquery-sqlalchemy 库。 table_android.exceptions 列结构是这样的: 在此处输入图像描述 列类型: 在此处输入图像描述

我在 bigquery 编辑器中看到了正确的结果。 但是 sqlalchemy 没有显示正确的结果。 我应该如何编辑我的 sqlalchemy 查询以获得正确的结果?

我没有 bigquery 所以我无法测试这个但我认为你想要column而不是literal_column 此外,我认为您可以通过在select_from中包含表和未嵌套的列来创建隐式CROSS JOIN


# I'm testing with postgresql but it doesn't have easy to make structs
from sqlalchemy.dialects import postgresql

table_android = Table("table_android", metadata,
                      Column("id", Integer, primary_key=True),
                      Column("exceptions", postgresql.ARRAY(String)),
                      Column("event_timestamp", Date))

from sqlalchemy.sql import column, func, select

d = func.unnest(table_android.c.exceptions).alias("d")
# You might be able to do d.column["type"].label("Error_Type")
type_col = column("d.type").label("Error_Type")
count_col = func.count(type_col).label("count")

print (select(
    type_col,
    count_col,
)
.select_from(table_android, d)
.group_by(type_col)
.order_by(count_col)
.where(table_android.c.event_timestamp.between('2022-12-15', '2022-12-20'))
.cte("main_table"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM