我有一张调查答案表,类似:
date | q1 | q2 | 12/12/10 | yes | no | 12/13/10 | no | no |
并且我想创建一个查询,该查询将为我提供该表的结果摘要,从而允许我设置相关的日期范围。我下面的声明非常有效:
SELECT ( SELECT Count(*) FROM `survey` WHERE q1='Yes') AS q1_yes, ( SELECT Count(*) FROM `survey` WHERE q1='No') AS q1_no, ( SELECT Count(*) FROM `survey` WHERE q2='Yes') AS q2_yes)
但是我不确定是否可以做得更好,以及在哪里添加日期范围过滤功能。
来自多刺的诺曼的第一个查询将给出这样的结果:
q1 q2 count(*) no yes 2 yes no 1 yes yes 1
仅将几组不同的结果分组。我假设您想按问题将是/否的总数分类。在这种情况下,您必须执行以下操作:
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
结果:
Question Answer Count q1 no 2 q1 yes 2 q2 no 1 q2 yes 3