Error with Pivot & Custom Expression

Hi All,

I'm building a financial pivot report with Metabase and I'm having trouble creating a custom expression to display in my pivot. Below you can see my settings. I've created a custom Postgresql Query which is in the LOE NET Union Query below. The data resolves as expected in a tabular format with two measure fields (volume and amount).

Below that I am Summarizing the "amount" field by the following criteria: tblid (which is my report section), Sort group, sort code, account name and journal date. Pretty straight forward and both queries resolve properly. I can display a pivot table of that data with the SUM of the 'amount' field without an issue.

What I really need to do is specify the displayed value based on the report section. In section 1: Sum of the volume. In section 2: Sum of Amount / Sum of volume. Section 3: Sum of amount.

To that end I did the following:

When I visualize that, I get an error:

ERROR: column "source.tblid" must appear in the GROUP BY clause or be used in an aggregate function
  Position: 181

When I run the 'SQL for this question' in Postgres, it works without error:

Is this a bug and/or is there a workaround?

Thanks for reading this far.

Thanks to Grok for pointing this out. Adding the aggregation expression to the tblid field in the case expression solved the issue. The error indicated that I could use tblid in the GROUP BY or an aggregation function but I really needed both.