0

Using MySQL. I have a table that looks like this:

   rawID | a1a | a1b | a2a | a2b | a2c | ...
     1   |  2  |  0  |  0  |  0  |  2  | ...
     2   |  2  |  2  |  0  |  0  |  0  | ...
     3   |  0  |  1  |  1  |  1  |  2  | ...
     4   |  2  |  1  |  2  |  1  |  2  | ...

*The possible values for the fields are predefined in a separate "response" table and range from 0-2.

I want a result that gives me the occurence of each value for each field. I've seen similar questions as this, but only ever deal with one field.

I would like my result to look like this:

   response | a1a | a1b | a2a | a2b | a2c | ...
      0     |  1  |  1  |  2  |  2  |  1  | ...
      1     |  0  |  2  |  1  |  2  |  0  | ...
      2     |  3  |  1  |  1  |  0  |  3  | ...

This table has the number of times each value ("response") occurred for each field.

Thanks guys,

4

2 回答 2

1

试试这个:

SELECT
  response,
  sum(a1a = response) a1aCount,
  sum(a1b = response) a1bCount,
  sum(a2a = response) a2aCount,
  sum(a2b = response) a2bCount,
  sum(a2c = response) a2cCount
FROM t, r
GROUP BY response

输出:

| RESPONSE | A1ACOUNT | A1BCOUNT | A2ACOUNT | A2BCOUNT | A2CCOUNT |
|----------|----------|----------|----------|----------|----------|
|        0 |        1 |        1 |        2 |        2 |        1 |
|        1 |        0 |        2 |        1 |        2 |        0 |
|        2 |        3 |        1 |        1 |        0 |        3 |

在这里拉小提琴。

无论response表中的项目数量如何,这都将起作用。

于 2013-10-23T22:08:56.537 回答
0

我认为这应该有效(我们假设您的表名是“responses”):

SELECT 0 as response, SUM(r.a1a = 0) as a1a, SUM(r.a1b = 0) as a1b,
SUM(r.a2a = 0) as a2a, SUM(r.a2b = 0) as a2b FROM responses r
UNION
SELECT 1 as response, SUM(r.a1a = 1) as a1a, SUM(r.a1b = 1) as a1b, 
SUM(r.a2a = 1) as a2a, SUM(r.a2b = 1) as a2b FROM responses r
UNION
SELECT 2 as response, SUM(r.a1a = 2) as a1a, SUM(r.a1b = 2) as a1b,    
SUM(r.a2a = 2) as a2a, SUM(r.a2b = 2) as a2b FROM responses r
于 2013-10-23T22:03:52.347 回答