Making statistics

Hi,

I’m really having trouble working with statistics in HA. Something which seems extremely easy in SQL (a single query and a group by) makes it super complex and time consuming to achieve the same in HA.

What I want to achieve:

I’m working on a battery project, which charges and discharges from the net (AC). I want to make a bar graph with each hour how much it charged or discharged and how much it did cost (based on energy price).
My sensor provides a total counter (kWh) counting up for charge energy and the same for discharge energy.
Other then that, I’m using tibber for energy rates.

I’ve tried using an utility meter, but this keeps counting up every 5 minutes and reset each hour; so that’s still something I can’t use to calculate the cost per hour with.

Other then that it would be great to do aggegrations per month or per year on total charge cost, discharge cost etc.

What would be the best way to do this? I’m already struggling the last few days acomplishing this but I’m really stranded.

Also, using history data to calculate this would be great. Everytime i make a new entity, it’s only based on new data, not on thei history.