Need help with a database query

We are using Matomo on our Intranet and use custom variables to track similar data in 30 websites. I want to be able to run a query against the Matomo database each month to extract the custom variables for each site. The data extracted will be used to populate a separate table which will then be exported into Excel.

I realize I will have to probably write a script which loops through all of the site ids for the 30 websites.

I tried running queries on the log_visit table since it contains the custom variable columns, but the numbers I got don’t exactly match the numbers from a Matomo report. I am guessing it somehow has to do with dates.

Can somebody help me get started?