如何从具有单个SELECT语句的表中获取多个计数

时间:2015-06-26 08:36:27

标签: mysql sql select count

这个查询看起来有逻辑错误所以不能给出我想要的东西。我希望我在下面解释清楚。你能帮帮我吗?

    SELECT a.CreateBy, CreateDate,
      (SELECT COUNT(*) FROM MyTable WHERE Item1=1) as Item1Count,
      (SELECT COUNT(*) FROM MyTable WHERE Item1=2) as Item2Count,
      (SELECT COUNT(*) FROM MyTable WHERE Item1=3) as Item3Count
    FROM MyTable a;

MyTable的

Id   | CreateBy | CreateDate  | Item1 | Item2 | Item3
-----------------------------------------------------
100  | John     | 01.06.2015  |  1    |   0   |   1
101  | John     | 01.06.2015  |  1    |   1   |   1
102  | Ahn      | 01.06.2015  |  0    |   1   |   0
103  | Patrick  | 01.06.2015  |  1    |   1   |   0
104  | John     | 02.06.2015  |  1    |   0   |   1

我想获得如下数据。

CreateBy | CreateDate | Item1Count | Item2Count | Item3Count
------------------------------------------------------------
John     | 01.06.2015 |     2     |      1      |    2
John     | 02.06.2015 |     1     |      0      |    1
Patrick  | 01.06.2015 |     1     |      1      |    0
Ahn      | 01.06.2015 |     0     |      1      |    0

1 个答案:

答案 0 :(得分:4)

您可以使用条件求和,然后按某种方式分组

select 
CreateBy,
CreateDate,
sum(Item1=1) as Item1Count,
sum(Item2=1) as Item2Count,
sum(Item3=1) as Item3Count
from MyTable
group by CreateBy,CreateDate