Skip to content
Advertisement

Is there a way to return non existent values when using groupby and union all?

I have a table that I’m trying to return summarized results from for a chart that will have two datasets, one for debit transactions that have happened each month and one for payments that have happened each month. The table I’m querying looks like this:

What I’m looking to get back out of my query is a result that does a sum(amount) once for each type and unions them together so that the result looks something like this:

So far I’ve gotten to the below query which returns mostly the right data but in the wrong format.

This returns the below, which you can see returns one row for each type, but doesn’t return a row if there is no values to sum. I could work with this format if I could have it return 2 rows for each month (one for each type) and if there is no values return 0.

What I can’t figure out is if there is a way to either return the above with non-existent values getting filled in with 0 or if there is a way to do sum(amount) twice, once for each type as separate columns.

Advertisement

Answer

If I follow you correctly, you can use conditional aggregation:

I used year_month instead of the name of the month, since you probably want to not count the same month in different years together. You can change that to something else if you want otherwise.

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