### Count（）返回total而不是count

I have qualified risks with description and creation date, who are attached to subcategory of risks this last ones are attached to category of risks, each risk has a name like 'Risk_1' , my aim is to count the number of risks by month and risk category including zero.

I have this request :

``````SELECT DISTINCT risk_names.type as risk_name, MONTH(risk.creation_date) as month, count(risk.id) as number FROM risk As risk , risk_category
JOIN  (
SELECT risk_category.name as type
FROM
risk_category
) as risk_names on risk_names.type = risk_category.name
where risk.creation_date >= (NOW()-INTERVAL 3 MONTH) GROUP BY MONTH(risk.creation_date), risk_names.type;
``````

Who return this result :

``````Risk_name          month  number
---------------------------------
Risk_1              1      10   ---> instead 8
Risk_2              1      10   ---> instead 1
Risk_3              1      10   ---> instead 1
Risk_1              2      12  ......
Risk_2              2      12
Risk_3              2      12
Risk_1              12     4
Risk_2              12     4
Risk_3              12     4
``````

As you can see the number returned is the total for each month , but my aim is to get total for each distinct risk. Can you help me . thanks

## 2 个解决方案

### #1

1

The comma in your `FROM` is doing a `CROSS JOIN`. A Cartesian product is unnecessary and throws all the counts off.

FROM中的逗号正在进行CROSS JOIN。笛卡尔积是不必要的，并将所有计数都抛弃。

I suspect you want something like this:

``````SELECT rc.type as risk_name, MONTH(r.creation_date) as month,
count(r.id) as number
FROM risk_category rc LEFT JOIN
risk r
ON r.?? = rc.??
where risk.creation_date >= (NOW()-INTERVAL 3 MONTH)
GROUP BY rc.type, MONTH(r.creation_date);
``````

I don't know what the `JOIN` criterion is between `risk` and `risk_category`.

### #2

0

Then try using `distinct` keuword with `count()` like `count(distinct risk.id) as number` instead 