Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

sql - Adding a calculated column while joining tables in Snowflake

I have 4 tables A, B, C and D with 3 columns each

A-  aa, ab, ac

B-  ba, bb, bc

C-  ca, cb, cc

D-  da, db, dc 

I need to join the 4 tables and add a new calculated column (aa + ab + ac). My query is

SELECT A.aa, A.ab, A.ac, B.ba, B.bb, B.bc, C.ca, C.cb, C.cc, D.da, D.db, D.dc,(A.aa + A.ab + A.ac) AS total

FROM A 

LEFT JOIN B

ON A.aa = B.ba

LEFT JOIN C

ON A.ab = C.ca

LEFT JOIN D

ON A.aa = D.da;

The tables join fine, but the calculated column returns NULL for all rows. Where am I going wrong and is there any other way to do it?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For completeness, moving the answer from @Fred from a comment to an answer:

Seems like some of aa, ab, ac are NULLs so sum is therefore NULL. Apply ZEROIFNULL() function to each column before summing, to treat missing values as zero?

https://docs.snowflake.com/en/sql-reference/functions/zeroifnull.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...