Support Questions

Find answers, ask questions, and share your expertise

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).