2017-07-18 139 views
1

在谷歌的bigquery,讓我說我想嘗試找到一個完全匹配(例如:通過郵政編碼),但如果我失敗了,根據說城市+狀態得到另一個更接近的匹配+國家。如何構建一個查詢來返回一個結果

因此,像:

select * 
from locations 
where 
    Target_Type = "Postal Code" and 
    Name = "L4A" and 
    Country_Code = "CA" 
    or 
    (
    Name = "Toronto" and 
    Target_Type = "City" and 
    Country_Code = "CA" 
) 

這將返回兩個,我想只是第一場比賽,第二隻在第一場比賽失敗。

如何做到這一點?

回答

1

創建一個虛擬字段以指示哪一個具有更高的優先級。並使用UNION同時進行搜索。

SELECT '1st Match' as priority, <some fields> 
FROM YourTable 
WHERE <some conditions> 
UNION ALL 
SELECT '2st Match' as priority, <some fields> 
FROM YourTable 
WHERE <other conditions> 
ORDER BY priority, <other sort field> -- in case query return multiple result 
LIMIT 1 
+0

你確定你的答案適用於BigQuery的?我收到錯誤無法識別令牌UNION。 – Carmageddon

+1

我不熟悉大查詢,但看起來像支持'UNION ALL' https://chartio.com/resources/tutorials/how-to-union-queries-in-google-bigquery/ –

+1

@Carmageddon它應該工作。嘗試在查詢的開始部分添加#standardSQL –

2

BigQuery的標準SQL - 又一個值得考慮的選擇 - 它允許你添加更多的「規則」比只有兩個在你的榜樣

#standardSQL 
WITH locations AS (
    SELECT "Postal Code" AS Target_Type, "L4A" AS Name, "CA" AS Country_Code UNION ALL 
    SELECT "City", "Toronto", "CA" 
) 
SELECT * 
FROM locations 
WHERE (
    Target_Type = "Postal Code" AND 
    Name = "L4A" AND 
    Country_Code = "CA" 
) OR (
    Name = "Toronto" AND 
    Target_Type = "City"AND 
    Country_Code = "CA" 
) 
ORDER BY CASE Target_Type 
    WHEN "Postal Code" THEN 1 
    WHEN "City" THEN 2 
    ELSE 3 END 
LIMIT 1 
+0

HI MB ,你寫了一本書,我的答案在BigQuery中工作嗎?或者我離開? –

+0

@JuanCarlosOropeza - 是的 - 該語法應與BigQuery一起使用 –

相關問題