Skip to content

Creating a query containing a SUM() of MAX() values with conditions

I have two tables:

Meter (condensed)

Tariff

I’m trying to create a query on the consumption with some conditions:

  • It must only look at consumption values between “peak hours” (15, 15.5, 16, …, 19.5, 20, 20.5).
  • For each day, find the highest (MAX) value and multiply by the tariff CHARGE. Call this Peak_Charge.
  • SUM the Peak_Charge values for each day into a Total_Peak_Charge value.

e.g. In the above tables, the MAX of day 2016-01-01 in peak hours is 0.0469 and day 2016-01-02 is 0.048. With these, I need to return a Total_Peak_Charge value that is equal to (0.0469 * 13.38) + (0.048 * 13.38) = 1.269762.

Advertisement

Answer

In your question you don’t clarify how Meter is related to Tariff.
If the columns Meter.meter_id and Tariff.id are related then join the tables, aggregate and then use window function sum():

If the 2 tables are unrelated and Tariff contains only 1 row, then:

See the demo.
Results:

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