Optimize query question/help
I have the current query that gets the total average of coffee consumption per day, there can be multiple logs with the same date. Wondering if using a subquery is the best way to do it? are there any helpers that can reduce the query size?
6 Replies
Since your date field is a date column, you can divide the total number of ids by the distinct number of dates.
Oh I forgot you can do something like that although It doesn't seem to get the correct result, it brings back "1" instead of "1.714", I'll keep looking into using your idea, thanks !!
count(distinct ${log.date}) brings out 7
count(${log.id}) brings out 12
which is correct, but it doesnt seem to be doing the division 🤔
I forgot you need to cast the first count as a decimal
Otherwise it converts to an integer
oh interesting I was thinking it was something regarding that but didn't know the syntax, is there any docs to read about "::decimal" cast?
it worked this time by the way, thank you!!
Count is cast as an integer by default
https://www.postgresqltutorial.com/postgresql-tutorial/postgresql-cast/
admin
PostgreSQL Tutorial
PostgreSQL CAST: Convert a Value of One Data Type to Another
You will learn how to use the PostgreSQL CAST() function and cast operator (::) to cast a value of one type to another.
thanks!!