Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium


General SQL (SQLite): Sum/Count based on values in the dataset

Posted on 2005-04-07
Medium Priority
Last Modified: 2012-06-27
I have a database in SQLite (which supports subqueries and standard aggregate functions).

One table describes the structure (chapters), one stores answers to questions, related to each chapter, and one table stores answer types. I want to get out data on each chapter, with a count on each of the values in the answer type table.

The data model is (simplified) like this:

Table Structure
| Field       |  Type      |
| Chapter     | int        |
| Description | varchar    |
Table Answer
| Field     |  Type    |
| Answer    | int      |
| Chapter   | int      |
Table AnswerOption
| Field       |  Type      |
| AnswerOptId | int        | (relates to Answer.Answer)
| Description | varchar    |

I would really like one(!) query that gives a result like this:
| Chapter | Value 1 | Value 2 | Value 3 | Value 4 |
|       1 |       3 |       2 |      15 |       6 |
|       2 |      11 |       0 |       7 |      16 |
|       3 |       6 |       1 |      12 |       1 |
Where Value N corresponds to each row in the AnswerOption table.

Please let me know if you need more information - the question is complicated to explain, but might be even harder to crack :)

Question by:henrikba
  • 2

Expert Comment

ID: 13733930

 My understanding is you have three table as
1. Table Structure - fields - Chapter,Descripition.
2. Table Answer - fields - Chapter,Answer
3. Table AnswerOption -fields - Answer,Answeroption,description.

now you have to find the sum and count of each chapter field in first table.

you can generate Query as

Query1 = select tablestructure.chapter,count(answer) as value1,Sum(answer) as value2 from tablestructure,TableAnswer where tablestructure.chapter = tableAnswer.chapter Group by tablestructure.chapter

Query2 = select tableanswer.chapter,count(answeroption) as value3,sum(answeroption) as value4 from tableAnswer,tableAnswerOption where tableanswer.Answer = tableansweroption.answer Group by tableanswer.chapter

Result Query = select Query1.Chapter,value1,value2,value3,value4 from Query1,Query2 where Query1.Chapter = Query2.Chapter

I think this will help you, if you have question let me know.


Accepted Solution

mar1ner earned 2000 total points
ID: 14012322
I've been struggeling with something much similar, but couldn't find a pure sql(ite)-solution. I'm using sqlite and php5 and found the sqlite_create_aggregate function.

So one suggestion is to investigate if the environment you're programming in has this (or a smimilar) function. php-documentation: http://www.php.net/manual/en/function.sqlite-create-function.php

Here is an example, assuming table Answer allow dupicates (otherwise it gives no meaning):

$dbhandle = sqlite_open('testing.sqlite');

function i_sum_step(&$context, $ans ,$key)
  if( $ans == $key )

function i_sum_finalize(&$context)
   return $context;

sqlite_create_aggregate($dbhandle, 'i_sum', 'i_sum_step', 'i_sum_finalize',2);

  select Structure.Description,
            i_sum(Answer.Answer,1) as value1,
            i_sum(Answer.Answer,2) as value2,
            i_sum(Answer.Answer,3) as value3,
            i_sum(Answer.Answer,4) as value4
  from Structure
  inner join Answer on Structure.Chapter=Answer.Chapter
  group by Structure.Chapter
  order by Structure.Chapter


- mar1ner


Author Comment

ID: 14043946
Hi, guys!!
Terribly sorry for the long wait; I've been on vacation and totally forgot all about this case.
I'll check both solutions today and get back to you ASAP.

Author Comment

ID: 14055145
mar1ner; thanks a lot for this comprehensive solution! I have now tried it in my own project and it turns out to work perfectly with some adaption to my slightly more complex datamodel.

Works exactly as I wanted, and now my reports are much faster than with recursive and numerous queries.

Thanks again :)

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this blog post, we’ll look at how using thread_statistics can cause high memory usage.
Instead of error trapping or hard-coding for non-updateable fields when using QODBC, let VBA automatically disable them when forms open. This way, users can view but not change the data. Part 1 explained how to use schema tables to do this. Part 2 h…
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …
Suggested Courses

577 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question