MySql统计每个字段

时间:2013-08-27 21:21:40

标签: mysql

我遇到Query问题。请有人帮帮我

让我们考虑一下这样的表格。 我们将0存储为no,将1存储为yes 。对于某些表,我们使用1表示是,2表示否。每个月我们都会向客户发送调查问题,他们会勾选是或否

+----------------------------------------------------------------------+
| id| Month | Customer | QuestionA | QuestionB | QuestionC | QuestionD |
+---+-------+----------+-----------+-----------+-----------+-----------+
| 1 | Jan   |  1100    |  1        |   0       |    1      |  0        |
| 2 | Jan   |  1101    |  0        |   0       |    1      |  1        |
| 3 | Jan   |  1102    |  1        |   1       |    1      |  1        |
| 4 | Feb   |  1100    |  1        |   1       |    0      |  1        |
| 5 | Mar   |  1100    |  1        |   1       |    0      |  0        |
+---+-------+----------+-----------+-----------+-----------+-----------+

我如何编写一个查询,显示每个问题有多少勾选是。换句话说,对于jan我需要得到像

+------------------------------------------------------------------+
| Month | Customer | QuestionA | QuestionB | QuestionC | QuestionD |
+-------+----------+-----------+-----------+-----------+-----------+
| Jan   |  1100    |  2        |   1       |    3      |  2        |
+-------+----------+-----------+-----------+-----------+-----------+

即QuestionA由2个客户签署,Questionb由1签署,所以......

修改

但在某些表格中,我们使用1表示是,2表示否。该怎么做对不起,我们已经设计了这样,它已被使用超过3年。所以他们不会允许我将0改为0而将1改为是

3 个答案:

答案 0 :(得分:0)

尚未测试,但您可以试试这个。告诉我结果,以便我们可以在必要时进行更新。

select month, sum(QuestionA), sum(QuestionB), sum(QuestionC), sum(QuestionD) from table_name where month='Jan'

答案 1 :(得分:0)

这应该有效,你需要看看如果你没有年份字段会发生什么,并且明年1月就会出现...你还需要一年字段,这样你就可以按月和年分组

SELECT
  `Month`,
  SUM(`QuestionA`) AS `QuestionA`,
  SUM(`QuestionB`) AS `QuestionB`,
  SUM(`QuestionC`) AS `QuestionC`,
  SUM(`QuestionD`) AS `QuestionD`
FROM
  tblsurvery
GROUP BY
  `Month`

修改

<强> thanks but in some table we have used 1 for yes and 2 for no

SELECT
  `Month`,
  SUM(IF(`QuestionA`=1,1,0) AS `QuestionA`,
  SUM(IF(`QuestionB`=1,1,0) AS `QuestionB`,
  SUM(IF(`QuestionC`=1,1,0) AS `QuestionC`,
  SUM(IF(`QuestionD`=1,1,0) AS `QuestionD`
FROM
  tblsurvery
GROUP BY
  `Month`

答案 2 :(得分:0)

如果不需要客户字段(我怀疑的话),您可以尝试:

SELECT
    month,
    SUM(IF(QuestionA=1,1,0)) AS QuestionA,
    SUM(IF(QuestionB=1,1,0)) AS QuestionB,
    SUM(IF(QuestionC=1,1,0)) AS QuestionC,
    SUM(IF(QuestionD=1,1,0)) AS QuestionD
FROM survey
GROUP BY month;

请参阅SQLFIDDLE:http://www.sqlfiddle.com/#!2/19a56/3/0

如果您需要,请尝试:

SELECT
    month, min(customer),
    SUM(IF(QuestionA=1,1,0)) AS QuestionA,
    SUM(IF(QuestionB=1,1,0)) AS QuestionB,
    SUM(IF(QuestionC=1,1,0)) AS QuestionC,
    SUM(IF(QuestionD=1,1,0)) AS QuestionD
FROM survey
GROUP BY month;

请参阅SQLFIDDLE:http://www.sqlfiddle.com/#!2/19a56/6/0