在JOIN的ON子句中使用别名

时间:2014-12-18 02:47:17

标签: sql join google-bigquery case-sensitive on-clause

Stack Overflow的新手(以及一般的编码)。

我做了一些研究,但无法找到以下问题的答案:

如何将两个表连接到应用于维度的函数结果,而不是维度本身?

即。我想在函数lower()的小写结果上加入以下两个表,而不是像它们一样加入大小写不明确的维度。

SELECT
lower(first_name) as firstname
,lower(last_name) as lastname
,lower(email) as email1
,total_donated
From BensData.Donations As a

JOIN EACH

(Select
lower(first_name) as first
,lower(last_name) as last
,lower(email) as email2
,sum(amount) as total_donated
From BensData.Donations 
GROUP BY email2, first, last) As b

ON a.email1=b.email2 AND a.firstname=b.first AND a.lastname=b.last

它不允许我加入我在第一个表(a)中创建的别名,但是,如果我在表a(first_name和last_name)中加入ON原始维度,那么结果将基于大小写不明确的维度,并给出不希望的结果。

我希望这很清楚。

感谢您的帮助!

3 个答案:

答案 0 :(得分:3)

尝试使用两个子查询:

SELECT
a.firstname
,a.lastname
,a.email1
,a.total_donated
FROM

(SELECT
lower(first_name) as firstname
,lower(last_name) as lastname
,lower(email) as email1
,total_donated
From BensData.Donations) As a

JOIN EACH

(Select
lower(first_name) as first
,lower(last_name) as last
,lower(email) as email2
,sum(amount) as total_donated
From BensData.Donations 
GROUP BY email2, first, last) As b

ON a.email1=b.email2 AND a.firstname=b.first AND a.lastname=b.last

在原始查询中,a只是BensData.Donations的别名,因此您只能加入该表中的字段。

答案 1 :(得分:0)

我从来没有听说过join each,也没有记录为MySQL连接的语法(见这里)。

试试这个from条款:

From BensData.Donations a JOIN
     (Select lower(first_name) as first, lower(last_name) as last,
             sum(amount) as total_donated
      From BensData.Donations 
      GROUP BY first, last
     ) b
     ON a.firstname = b.first AND a.lastname = b.last

您的版本在列之间的子查询中也缺少逗号。

为清楚起见,您应该将from子句写为:

     ON lower(a.firstname) = b.first AND lower(a.lastname) = b.last

或从子查询中删除lower()。否则,您依赖于服务器,数据库和表的默认排序规则,以了解on子句的实际内容。

答案 2 :(得分:0)

感谢大家的帮助!

特别是指向我正确方向的链轮!他和我的代码的主要区别在于我没有在第一个SELECT子句的每个维度的前面附加表别名(例如** a。** fistname,** a。** lastname,--- - >名字,姓氏)

由于某些原因,BigQuery因为表别名而一直给我一个错误。

这是有效的代码。

SELECT
firstname
,lastname
,email1
,total_donated
FROM

(SELECT
lower(first_name) as firstname
,lower(last_name) as lastname
,lower(email) as email1
From BensData.Donations) As a

JOIN EACH

(Select
lower(first_name) as first
,lower(last_name) as last
,lower(email) as email2
,sum(float(amount)) as total_donated
From BensData.Donations 
GROUP BY email2, first, last) As b

ON a.email1=b.email2 AND a.firstname=b.first AND a.lastname=b.last

感谢大家的帮助!