Skip to content
Advertisement

SQL Subquery with aggregate function – seeking alternative

My table (Table1)

I did a sort of Pivot and it’s fine: http://sqlfiddle.com/#!18/45b9d/1/0

Now I need to calculate the difference between measures, to get something like this:

But if I don’t use an aggregate, the result brings me null cells – http://sqlfiddle.com/#!18/45b9d/5/0

And if I do use it, I get the message:

Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

Any help would be great.

Advertisement

Answer

You can use window functions. Starting from your existing conditional aggregation query, this computes the consumption difference between the current and previous date for each house:

The subquery is not technically necessary, but it avoids repeating the conditional sum()s twice.

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