linking database when primary key is not id and doing some counting

Hello all,

I am adding one more question to my previous posting.

I have 2 tables that I had created with migrations, but these are based on existing database. So the automatically created id column is not used. These tables have the following structure.