汇总单个表中多列的计数

时间:2016-06-26 16:06:24

标签: mysql aggregate-functions

我想在单个显示器上显示两个类别的数据计数

我的表如下:

table : funding
area        client      Donatur
-----------------------------------------
A        Ox      Mr.X
A        Pr      Mr.Y
A        Qs      Mr.Z
A        Ts      Mr.Z   
B        Rt      Mr.X
C        Ss      Mr.X   
C        Sa      Mr.Z   

我希望显示基于区域和donatur的数据,如下表所示

Donatur     Count of Area   Count of Client
--------------------------------------------------------
Mr.X          3             3
Mr.Y          1             1
Mr.Z          2             3

我尝试创建如下的查询:

从资金分组中选择计数(客户),计数(区域),donatur

但我不能在一方获得任何正确的数字,结果如下,两者都相同。它'应该像上面那样

Donatur     Count of Area       Count of Client
--------------------------------------------------------
Mr.X          3             3
Mr.Y          1             1
Mr.Z          2             2

2 个答案:

答案 0 :(得分:3)

mysql> SELECT DONATUR,COUNT(DISTINCT AREA) AS AREA,COUNT(DISTINCT CLIENT) AS CLIENT FROM funding GROUP BY Donatur;
+---------+------+--------+
| DONATUR | AREA | CLIENT |
+---------+------+--------+
| Mr.X    |    3 |      3 |
| Mr.Y    |    1 |      1 |
| Mr.Z    |    2 |      3 |
+---------+------+--------+
3 rows in set (0.00 sec)

答案 1 :(得分:2)

select donatur, count(distinct area), count(distinct client)
from funding 
group by donatur