我试图从本质上连接两个表,找到两个表之间的公用数字,弄清call_counterparty的名称并创建一个结果表。我希望它显示call_counterparty的号码,而不是要查询的号码,在我们的情况下是(from_number)。例如,如果您打电话给我,您将成为我的呼入对手,我将成为您的呼出对手。如果我给您打电话,您将是我的外拨电话对手,而我将是你的外拨电话对方。我不确定如何区分“ call_counterparty”。
简而言之,被查询人打谁电话或接听谁打来的电话,他们的相关名字是什么?如果要连接的表中没有对应的名称,则显示null。假设我的电话号码是2228881111 ...,假设您甚至可以打电话给自己。
我正在使用的两个BigQuery数据库表是:
bigquery.call_log_table
0
bigquery.contact_list_table
from_number,to_number
2228881111,9997772222
2228881111,8883337777
8883337777,2228881111
2228881111,1112229999
6663332222,2228881111
2228881111,2228881111
这是我当前没有左联接或其他代码的代码:
number,name
9997772222,John
8883337777,Jill
2228881111,Me
当前结果:
SELECT CASE WHEN call_log.from_number =
'2228881111' THEN
call_log.to_number ELSE call_log.from_number END AS
call_counterparty,
SUM(call_log.to_number = '2228881111') AS in_call,
SUM(call_log.from_number = '2228881111') AS out_call
FROM `bigquery.call_log_table` AS call_log
WHERE '2228881111' in (call_log.from_number, call_log.to_number)
GROUP BY call_counterparty
我想要的结果
call_counterparty,in_call,out_call
9997772222,0,1
8883337777,1,1
1112229999,0,1
6663332222,1,0
2228881111,1,1
我尝试了各种尝试,花了几个小时,用Google搜索了一吨,但我根本不知道。任何帮助将不胜感激!
答案 0 :(得分:2)
尝试这样的查询:
WITH call_records AS (
SELECT
CASE WHEN call_log.from_number = '2228881111' THEN call_log.to_number ELSE call_log.from_number END AS call_counterparty
, SUM(IF(call_log.to_number = '2228881111',1,0)) AS in_call
, SUM(IF(call_log.from_number = '2228881111',1,0)) AS out_call
FROM `dataset.call_log_table` AS call_log
WHERE '2228881111' in (call_log.from_number, call_log.to_number)
GROUP BY call_counterparty
)
SELECT call_counterparty, contacts.name, in_call, out_call
FROM call_records
LEFT JOIN `dataset.contact_list_table` as contacts
ON call_records.call_counterparty = contacts.number
GROUP BY call_counterparty, contacts.name, in_call, out_call
答案 1 :(得分:0)
以下是用于BigQuery标准SQL
#standardSQL
SELECT
CASE WHEN call_log.from_number = '2228881111' THEN call_log.to_number ELSE call_log.from_number END AS call_counterparty
, contacts.name
, SUM(IF(call_log.to_number = '2228881111',1,0)) AS in_call
, SUM(IF(call_log.from_number = '2228881111',1,0)) AS out_call
FROM `project.dataset.call_log_table` AS call_log
LEFT JOIN `project.dataset.contact_list_table` AS contacts
ON contacts.number = CASE WHEN call_log.from_number = '2228881111' THEN call_log.to_number ELSE call_log.from_number END
WHERE '2228881111' IN (call_log.from_number, call_log.to_number)
GROUP BY call_counterparty, contacts.name