[英]Count() return total instead distinct 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( as number FROM risk As risk , risk_category
   JOIN  (
    SELECT as type
    ) as risk_names on risk_names.type =
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 个解决方案



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( 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.




Then try using distinct keuword with count() like count(distinct as number instead

然后尝试使用带有count()的distinct keuword,例如count(distinct作为数字



为什么DISTINCT COUNT()会返回9而不是1? - Why would DISTINCT COUNT() return 9 instead of 1? 为什么“SELECT COUNT(DISTINCT )FROM ”返回0? - Why “SELECT COUNT(DISTINCT ) FROM
” return 0?查询返回行而不是total? - MySQL count() query returns rows instead of total?使用myBatis返回ResultMap中的总行数 - Return total count of rows in ResultMap with myBatisMySQL - 返回不同的行和重复的计数 - MySQL - Return Distinct Rows and Count of their Duplicates选择Count(Distinct Value)返回1 - Select Count(Distinct Value) returns 1获得不同值的总数 - Getting total count of distinct values为什么mysql select count(distinct user_id)返回错误的数字? - Why mysql select count(distinct user_id) return wrong number?在烬数据“查找”或“findAll”请求中返回总行数 - Return count of total rows in ember data `find` or `findAll` requestfn:count给我1而不是总计数()数 - fn:count give me 1's instead of the total count() number
粤ICP备14056181号  © 2014-2020