[英]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