I’ve a complex query with SQLite that seeks to grab a total from 3 related tables.
The following is an example of my tables:
----
cities
----
id, name
----
surveys
----
id, cities_id
----
population
----
id, survey_id
I need to find the total number of surveyed people for each city.
Here’s the approach I’ve been taking using c#, but I believe there should be a straighter way to do this through SQLite. Plus, my brain is not solving my final step using c#.
//get a list of all cities
List<string> cities = new List<string>();
cmd.CommandText = "SELECT * from cities ";
cmd.ExecuteScalar();
SqlCeDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
list_cities.Add(myReader["id"].ToString().Trim());
}
//get survey ids related to these citities
List<list_key_val> list_survey_ids = new List<list_key_val>();
foreach (String city_id in cities)
{
cmd.CommandText = "SELECT * from surveys WHERE city_id = '" + city_id + "'";
cmd.ExecuteScalar();
SqlCeDataReader myReader = cmd.ExecuteReader();
while (myReader.Read())
{
list_survey_ids.Add(new list_key_val()
{
key = city_id,
val = myReader["id"].ToString().Trim()
});
}
}
//find total surveyed person count for each survey id.
List<list_key_val> list_surveyed_total = new List<list_key_val>();
foreach (String survey_id in list_survey_ids)
{
cmd.CommandText = "SELECT COUNT(*) from population WHERE survey_id = '" + survey_id + "'";
cmd.ExecuteScalar();
list_surveyed_total.Add(new list_key_val()
{
key = survey_id,
val = count = (int)cmd.ExecuteScalar();
}
}
//find surveyed count as city id -> survey id -> surveyed count
List<list_key_val> list_city_surveyed_total = new List<list_key_val>();
foreach (String city_id in list_cities)
{
//dar... complex nested key calculations here, possibly?
}
I understand that SQLite has some limitation when it comes to combining queries. Thank you for any and all help!
Hard to tell if I got it right but you should be able to perform the operation in a single query… something like:
Should give you something like:
Chicago, 1, 4000
Chicago, 2, 3355
Denver, 1, 2580
etc….
Ok, here is a dump of a test I just did in sqlite