0

我对 Query 有疑问。有人能帮帮我吗

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

+----------------------------------------------------------------------+
| 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 表示 yes ,使用 2 表示 no 。该怎么办。很抱歉,我们是这样设计的,并且已经使用了 3 年多。所以他们不允许我将 0 更改为否,将 1 更改为是

4

3 回答 3

0

这应该可行,你需要看看会发生什么,但如果你没有年份字段并且明年一月左右滚动......你还需要一个年份字段,这样你就可以按月和年分组

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`
于 2013-08-27T21:28:11.747 回答
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

于 2013-08-27T21:29:02.750 回答
0

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

select month, sum(QuestionA), sum(QuestionB), sum(QuestionC), sum(QuestionD) from table_name where month='Jan'
于 2013-08-27T21:25:43.327 回答