![](/img/trans.png)
[英]How to query a Google BigQuery table and remove duplicates based on a subset of columns?
[英]How to remove duplicates in query for google big query by a subset of returned rows, and keep first?
在熊貓中,我可以按列的子集刪除重復項並首先保留
df = df.drop_duplicates(subset=['column1', 'column6'], keep='first')
我試圖弄清楚如何在谷歌大查詢的查詢中做同樣的事情。
我看到 GROUP BY 是在這種情況下推薦的,所以我嘗試了類似的方法
query = """
SELECT
table1.column1,
table1.column2,
table1.column3,
table2.column4,
table2.column5,
table3.column6,
FROM table1
JOIN table2
ON
(
table1.columnA = table2.columnA
AND
table1.columnB = table2.columnB
AND
table1.columnC = table2.columnC
)
JOIN table3
ON
table3.column6 = table2.column6
GROUP BY
table1.column1
table3.column6
"""
我收到一個錯誤,例如
select list expression references tableX.columnY which is neither grouped nor aggregraed at [4:5]
看來,由於當我按要分組的列進行分組時,我有多個其他列值,所以出現錯誤。 在谷歌搜索之后,我發現我應該使用 DISTINCT ON 來為我的 GROUP BY 保留多個值中的第一個。 所以我嘗試了
query = """
SELECT DISTINCT ON (table1.column1, table3.column6)
table3.column6
table1.column1,
table1.column2,
table1.column3,
table2.column4,
table2.column5,
table3.column6,
FROM table1
JOIN table2
ON
(
table1.columnA = table2.columnA
AND
table1.columnB = table2.columnB
AND
table1.columnC = table2.columnC
)
JOIN table3
ON
table3.column6 = table2.column6
"""
但我現在收到一個錯誤,上面寫着類似
400 syntax error, unexpected keyword ON at
從搜索來看,Google Bigquery 似乎沒有使用 DISTINCT ON。 但我能找到的唯一解決方案是使用 GROUP BY,它已經不起作用了。
因此,在查詢中,如何刪除列子集的重復項,並刪除按該子集分組的行對其他列有多個值。
在查詢后基於子集進行重復數據刪除的解決方案對我不起作用,因為我的問題是由於返回大量行,沒有重復數據刪除的查詢需要很長時間才能完成。
正如@Jaytiger 在評論中提到的那樣,我們必須使用ROW_NUMBER()
函數以及PARTITION BY
和ORDER BY
子句。
考慮下面的查詢。 我已經對樣本數據的查詢進行了測試,並將結果與 pandas 片段的結果進行了比較。
SELECT * from
(
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY column1, column6 ORDER BY columnX) row_num
FROM
`<project-id>.test_dataset.keep_first_in_duplicate`
)
where row_num=1
ORDER BY
子句的使用取決於需求,需求是輸入數據的順序保存。 與 pandas 數據框不同,BigQuery 中不保留輸入數據的順序。 如果我們希望保留順序,我們必須有一個帶有索引的新列,可用於在提取到 BigQuery 后對數據進行排序。 綜上所述,如果你的數據源遵循一定的順序,那么 BigQuery 的去重輸出和 pandas 數據框的去重輸出就會有差異。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.