简体   繁体   English

MySQL查询没有返回正确的百分比

[英]mysql query not returning correct percentage

I have a table where I am trying to get select results, with a date clause. 我有一个表,我试图获取带有日期子句的选择结果。 Group by column, count the total of another column and then work out the percentage of that count associated with the grouped column. 按列分组,计算另一列的总数,然后计算出与分组列关联的计数的百分比。

ID | ID | Delaytype | 延迟类型 Delayhours |Delaydate 延迟时间|延迟时间

1 | 1 | type1 | 类型1 | 2 | 2 | 2015-01-10 2015-01-10

2 | 2 | type2 | type2 | 3 | 3 | 2015-01-10 2015-01-10

3 |type2 | 3 | type2 | 1 | 1 | 2015-02-10 2015-02-10

4 | 4 | type2 | type2 | 1 | 1 | 2015-01-10 2015-01-10

So a Query on the month of Jan should give me : type 1 = 33.3% type 2 = 66.6% 因此,对一月份的查询应该给我:类型1 = 33.3%类型2 = 66.6%

My query so far is : 到目前为止,我的查询是:

$result = mysqli_query($con, "SELECT Delaytype, SUM(`Delayhours`) / (SELECT Sum(Delayhours)) 
        * 100 as cnt FROM delays  WHERE YEAR(Delaydate) = '".$yearly."' AND MONTH(Delaydate) = '".$month."' GROUP BY Delaytype; ");

However I am getting a 100% result for each Delaytype 但是我为每个Delaytype得到100%的结果

thankyou in advance for any help. 预先感谢您的任何帮助。

Cant see where I can make a table so I apologize for the formatting. 不能看到我可以在哪里摆桌子,所以我对格式表示歉意。

SELECT 
    DelayType,
    SUM(Delayhours) AS Delaytotal,
    ROUND(
        100*(
          SUM(Delayhours) / 
          (
              SELECT SUM(Delayhours) 
              FROM dummy 
              WHERE 
                  Delaydate >= '2015-01-01' AND
                  Delaydate < '2015-02-01'
          )
        ), 
        2
    ) AS Delaypercents
FROM dummy
WHERE 
    Delaydate >= '2015-01-01' AND 
    Delaydate < '2015-02-01'
GROUP BY Delaytype

And catch the fiddle :) 抓住小提琴:)

PS Thanks to Used_By_Already for new details. PS感谢Used_By_Already提供了新的详细信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM