Skip to content
Advertisement

How to calculate agregate values by condition?

here my base example

Try smth like this, but nothing

Could you help me?

Advertisement

Answer

UPDATE: for these, I have added a new column to allow ordering of the rows. As the OP referred to day_name as a number in code, I have assumed that they refer to days – and thus changed the ‘id’ column to ‘daynum’, and accordingly added a column ‘weeknum’.

Sorting by weeknum then daynum is equivalent to sorting by date. If the OP instead has a datefield as the key column to sort by, change my references to ORDER BY weeknum, daynum to ORDER BY datefield.

Here is the data setup I used (first two weeks only):

One relatively clear version would be to have a sub-query or CTE that finds all types of averages, then an outer query that selects the appropriate one e.g.,

A shorter way is just to include them in a single CASE expression

Here’s a db<>fiddle with data, and both options.

FYI here’s a db<>fiddle in SQL Server as that’s what I wrote it in first.

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