Count()返回total而不是count

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

我有描述和创建日期的合格风险,附加到风险子类别的风险,最后的风险属于风险类别,每个风险都有一个名称'Risk_1',我的目标是按月计算风险数量和风险类别包括零。

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.

我不知道风险和risk_category之间的JOIN标准是什么。

#2


0  

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

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

智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2017/03/16/7defea2357292a95a3530c5cebace75b.html



猜您在找
为什么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
智能推荐
 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告