要计算的Mysql逻辑

时间:2014-07-29 18:55:02

标签: mysql sql count

我的表格如下:

| id   | version | type | test_id | value |
+------+---------+----------+---------+--------------------+
| 1235 |       0 |  600 |     111 | 2     |
| 1236 |       0 |  600 |     111 | 2     |
| 1237 |       0 |  600 |     111 | 2     |
| 1238 |       0 |  601 |     111 | 1     |
| 1239 |       0 |  602 |     111 | 1     |
| 1240 |       0 |  600 |     111 | 1     |
| 1241 |       0 |  601 |     111 | 1     |

我试图检索列值的计数依赖项。类型600有三个值2和一个值1.所以我需要结果3和1.我的同事告诉我使用distinct但我认为我使用了错误的语法?

(select distinct a.type from Answer a where type = 600)
  union 
(select distinct a.value from Answer a where type = 600) 
  union 
(select count(value) from Answer where type = 600 and value = 2);

5 个答案:

答案 0 :(得分:2)

select value, count(*) from a where type=600 group by value

答案 1 :(得分:2)

这是你需要的吗?

SELECT type, value, COUNT(*)
FROM Answer
GROUP BY 1, 2;

答案 2 :(得分:1)

您可以按类型和值进行分组。

SQL Fiddle Example

 select type,
   value,
   count(*)
 from answer
 -- add your where clause
 group by type, value

答案 3 :(得分:0)

select type, count(value) 
from table
where type = 600
group by type

这不是你需要的全部吗?

答案 4 :(得分:0)

SELECT TYPE,VALUE,COUNT(*) FROM Answer 
GROUP BY type,value

您可以根据多个栏目进行分组,请参阅this question了解详情。