如何构造查询以返回一个结果

时间:2017-07-18 20:46:32

标签: sql google-bigquery

在google的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"
  )

这会返回两个,我想只获得第一场比赛,第二场比赛只有第一场比赛失败。

怎么做?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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