BigQuery SQL,获取中位数,按日期分组?
BigQuery SQL, Obtain Median, Grouped by Date?
当试图通过 window 函数使用分区获取中位数时,我收到一条错误消息“SELECT list expression references column seller_stock既不分组也不聚合”,这是为什么,我必须如何以不同的方式写这个SQL?我每天有很多记录,我想 return 每天的中位数 ...
SELECT date(snapshot_date) AS period,
PERCENTILE_DISC(**seller_stock**, 0.5) OVER (PARTITION BY snapshot_date) AS median_stock
FROM `table.name`
WHERE snapshot_date >= "2022-04-01"
GROUP BY snapshot_date
问题是您不能按 AGG 函数分组,因为您已经通过行获得中位数,您将只需要该语句的第一行。
您可以使用中级 table 或辅助
这是一个例子:
with median_data as (
select
date(snapshot_date) AS period,
PERCENTILE_DISC(seller_stock, 0.5) OVER (PARTITION BY snapshot_date) AS median_stock,
row_number() over(order by snapshot_date) as r
from `table.name`
where snapshot_date >= "2022-04-01"
)
select period,median_stock from median_data where r = 1
当试图通过 window 函数使用分区获取中位数时,我收到一条错误消息“SELECT list expression references column seller_stock既不分组也不聚合”,这是为什么,我必须如何以不同的方式写这个SQL?我每天有很多记录,我想 return 每天的中位数 ...
SELECT date(snapshot_date) AS period,
PERCENTILE_DISC(**seller_stock**, 0.5) OVER (PARTITION BY snapshot_date) AS median_stock
FROM `table.name`
WHERE snapshot_date >= "2022-04-01"
GROUP BY snapshot_date
问题是您不能按 AGG 函数分组,因为您已经通过行获得中位数,您将只需要该语句的第一行。
您可以使用中级 table 或辅助
这是一个例子:
with median_data as (
select
date(snapshot_date) AS period,
PERCENTILE_DISC(seller_stock, 0.5) OVER (PARTITION BY snapshot_date) AS median_stock,
row_number() over(order by snapshot_date) as r
from `table.name`
where snapshot_date >= "2022-04-01"
)
select period,median_stock from median_data where r = 1