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

Posted on 2005-04-07
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
    LVL 5

    Expert Comment


     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.

    LVL 1

    Accepted Solution

    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:

    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

    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

    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 :)

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Highfive + Dolby Voice = No More Audio Complaints!

    Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

    Introduction: Often, when running a query with joins, the results show up "duplicates", and often, those duplicates can be "eliminated" in the results using DISTINCT, for example. Using DISTINCT is simple: just add it after the SELECT keyword, an…
    CCModeler offers a way to enter basic information like entities, attributes and relationships and export them as yEd or erviz diagram. It also can import existing Access or SQL Server tables with relationships.
    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…
    Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

    779 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

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now