Skip to content
Advertisement

Redshift SQL sumup amount from two groups only when group 1 is found

I have a requirement where I have to add amounts from two groups only if first group exists.

So far, i have selected distinct groups and the corresponding ids. But i am not sure how to proceed further.

sample selected source Data :

Now i need to generate a table like below:

id, field1, field2, sum(amount) if (type = type1 and amount <> 0) or (type = type2 and amount <> 0), this should be done only when type 1 is present else no record created.

i.e. sample data to be generated

The code i have written (provided below) generates sum(amount) or amount even when type 1 is not there, Kindly help.

Thanks in advance…

Advertisement

Answer

This sounds like conditional aggregation with filtering:

This sums up the values for type1 and type2. The having clause makes sure that there is at least one row with 'type1'.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement