Our Community is getting an upgrade! To get everything ready for the relaunch, we’ll be placing the site in read-only mode starting September 21st.
We really appreciate your understanding while we get things set up behind the scenes. Catch up on all the exciting details about the move here.
Need help or have questions? Drop us a line at [email protected]

Support Questions

Find answers, ask questions, and share your expertise
Announcements
Share your experience with Cloudera on G2 and get a $25 Amazon Gift card.
Hi, I'm CLEO! Something exciting is coming to the Community. Stay Tuned!

Hive query to check sum of 2 rows against a 3rd row

avatar
Contributor

Hey all,

So I'm trying to check some columns together to ensure that the sums of A & B equal to row C, for each given currency.

 

Table Sales;

CurrencyColAColBColC
AUD50,00050,000100,000
CAD{null}20,00020,000
MZN30,000{null}30,000
YER10,00010,00020,000

Query that I can't seem to get working properly:

SELECT Currency,  CAST((SUM)CASE WHEN((coalesce(ColA,0)) + (coalesce(ColB,0))) = (coalesce(ColC,0)) THEN 0 ELSE SUM((coalesce(ColA,0)) + (coalesce(ColB,0))) - (coalesce(ColC,0) END AS sales_check)

The output that I'd like to get:

Currencysales_check
AUD0
CAD0
MZN0
YER0

Thanks,

2 REPLIES 2

avatar
Master Collaborator

Hi @Supernova ,

Can you try this below?

SELECT
Currency,
CASE
WHEN COALESCE(SUM(ColA), 0) + COALESCE(SUM(ColB), 0) = COALESCE(SUM(ColC), 0)
THEN 0
ELSE COALESCE(SUM(ColA), 0) + COALESCE(SUM(ColB), 0) - COALESCE(SUM(ColC), 0)
END AS sales_check
FROM Sales
GROUP BY Currency;

 

Regards,

Chethan YM

 

avatar
Contributor

After adding a ) to both lines(which Hive didn't like not having), it works for some of the currencies- but others are not adding up properly- ie, they'll double the negative values(when there).