Calculating average number of sessions per user
I have the following resource:
What I'm trying to do is calculate the average number of sessions per user. The SQL query we currently use for this is this:
Where
num_sessions
is the alias of a subquery, e.g. select user_id, count(user_id) AS num_sessions
.
I was told that this would need to be a calculation but I don't really know how to proceed with that.14 Replies
That results in an error that complains about a missing relationship:
you also need the relationship:
has_many :session_events, MyApp.Ash.Dashboards.SessionEvent
hence why I said since user has many session events 😅 I thought you already defined that relationshipDefine the relationship on the User resource?
yes. is it true that user has many sessions?
Yes. But they are on another database & repo
So there's no direct foreign-key association like you would normally have in a scenario like this
🤔 that's interesting. did you try? what happens?
just to check, you have two resources, user and session_event. one is looking at one db, the other on another, right?
correct
I got a feeling it should still work
session event has a column user_id which is the same as id of user from the other db
do try and let me know, now I'm curious ðŸ¤
Yesterday I tried it like this:
This resulted in:
So it's trying to join the tables and failing beacuse the table of the relationship doesn't exist in the database that the resource is in
okay, so there is Custom aggregates in the query
i.e. in
opts
for aggregate/4
you can give query
; you could construct your query regarding sessions, check if the query works. add filtering to it regarding user ids and what not.
give that query for the aggregate call.
maybe that could work 🤔But that doesn't solve the relationship problem, i.e. aggregates seem to require a relationship to be defined, and in this case we cannot define one because the other table is in another database
🤔 yea...
could you post the
postgres
sections from your resources? just to check
another idea 💡
there is Manual Relationship
maybe with that you could "load" the appropriate sessions from the other database
you would have
then you would create that module, use ManualRelationship and implement your load that queries your other database.
then you could use that relationship in an aggregate as mentioned aboveDo you need to be able to filter on this value?
Or are you just looking to compute it?
Ash doesn't have grouping except in aggregates, you'd use Ecto for that.
Something along those lines in a calculation
If you want to filter on it, then it's a fragment with a subquery unfortunately
fragment("(SELECT ...)")