获取 BigQuery 中最新行的属性?
Posted
技术标签:
【中文标题】获取 BigQuery 中最新行的属性?【英文标题】:Get the attributes of the most recent row in BigQuery? 【发布时间】:2017-04-12 11:26:48 【问题描述】:我在 BigQuery 工作。我有一张表t1
,其中包含地址、邮政编码、价格和日期字段。我想按地址和邮政编码对它进行分组,找到每个地址最近一行的价格。
如何在 BigQuery 中执行此操作?我知道如何获取地址、邮政编码和最近的日期:
SELECT
ADDRESS, POSTCODE, MAX(DATE)
FROM
[mytable]
GROUP BY
ADDRESS,
POSTCODE
但我不知道如何获取与这些字段匹配的这些行的价格。这是我最好的猜测,它确实会产生结果 - 这是正确的吗?
SELECT
t1.address, t1.postcode, t1.date, t2.price
FROM [mytable] t2
JOIN
(SELECT
ADDRESS, POSTCODE, MAX(DATE) AS date
FROM
[mytable]
GROUP BY
ADDRESS,
POSTCODE) t1
ON t1.address=t2.address
AND t1.postcode=t2.postcode
AND t1.date=t2.date
在我看来,这应该可行,但某些similar questions 的解决方案要复杂得多。
【问题讨论】:
嗯,我觉得应该是INNER JOIN
?
【参考方案1】:
只需使用row_number()
:
SELECT t.*
FROM (SELECT t.*,
ROW_NUMBER() OVER (PARTITION BY ADDRESS, POSTCODE
ORDER BY DATE DESC
) as seqnum
FROM [mytable] t
) t
WHERE seqnum = 1;
这不是聚合查询。您想要过滤行以获取最新值。
【讨论】:
谢谢!出于兴趣,为什么这比我的方法更可取? 除非您进行自加入,否则您的方法不允许您检索与最大日期相关的价格,而此方法不需要加入。您还可以查看我在 ***.com/a/43340019/6253347 中的回答,作为使用聚合函数选择最新行的示例。【参考方案2】:试试下面的 BigQuery 标准 SQL
#standardSQL
SELECT row.* FROM (
SELECT ARRAY_AGG(t ORDER BY date DESC LIMIT 1)[OFFSET(0)] AS row
FROM `yourTable` AS t
GROUP BY address, postcode
)
您可以使用如下的虚拟数据进行播放/测试
#standardSQL
WITH yourTable AS (
SELECT 'address_1' AS address, 'postcode_1' AS postcode, '2017-01-01' AS date, 1 AS price UNION ALL
SELECT 'address_1', 'postcode_1', '2017-01-02', 2 UNION ALL
SELECT 'address_1', 'postcode_1', '2017-01-03', 3 UNION ALL
SELECT 'address_1', 'postcode_1', '2017-01-04', 4 UNION ALL
SELECT 'address_2', 'postcode_2', '2017-01-01', 5 UNION ALL
SELECT 'address_3', 'postcode_1', '2017-01-01', 6 UNION ALL
SELECT 'address_3', 'postcode_1', '2017-01-02', 7 UNION ALL
SELECT 'address_3', 'postcode_1', '2017-01-03', 8
)
SELECT row.* FROM (
SELECT ARRAY_AGG(t ORDER BY date DESC LIMIT 1)[OFFSET(0)] AS row
FROM `yourTable` AS t
GROUP BY address, postcode
)
【讨论】:
你在 2017 年的回答帮助我在 2021 年解决了一个问题。谢谢你,米哈伊尔 :)以上是关于获取 BigQuery 中最新行的属性?的主要内容,如果未能解决你的问题,请参考以下文章