multiple select in one sql statement

后端 未结 2 688
Happy的楠姐
Happy的楠姐 2021-01-15 20:46

I have a table of survey answers, something like:

date     |  q1  | q2 |
12/12/10 | yes | no | 
12/13/10 | no  | no | 

and I would like to

相关标签:
2条回答
  • 2021-01-15 21:07

    The first query from spiny norman will give a result like that:

    q1    q2    count(*)
    no    yes   2
    yes   no    1
    yes   yes   1
    

    Which only groups couples of distinct results. I assume you want to group the overall number of yes/no by question. In that case, you'd have to do something like that:

    SELECT 'q1' as Question, s1.q1 as Answer, count(*) as Count
    FROM survey s1
    WHERE date>='2010-10-01' AND date<'2010-10-30'
    GROUP BY q1
    UNION
    SELECT 'q2' as Question, q2 as Answer, count(*) as Count
    FROM survey
    WHERE date>='2010-10-01' AND date<'2010-10-30'
    GROUP BY q2
    

    Result:

    Question Answer    Count
    q1       no        2
    q1       yes       2
    q2       no        1
    q2       yes       3
    
    0 讨论(0)
  • 2021-01-15 21:11

    You could use:

    select q1, q2, count(*)
    from survey
    group by q1, q2
    

    Or, if you want to get those exact same results:

    select count(case when q1 = 'Yes' then q1 else null end) as q1_yes,
           count(case when q1 = 'No' then q1 else null end) as q1_no,
           count(case when q2 = 'Yes' then q2 else null end) as q2_yes
    from survey
    

    Your implementation of "case" may vary, the important thing is you can set everything you don't want to null and it won't be counted by count() :)

    0 讨论(0)
提交回复
热议问题