使用MySQL计算行和查找平均值的总和

时间:2017-03-14 11:15:39

标签: mysql count average

我有两张表 App 商店

  • 分组:分组的应用程序计数,即HasGroup = 1
  • NonGrouped:未分组的应用程序计数,即HasGroup = 0
  • 分组(%):分组的应用程序的百分比,即HasGroup = 1
  • NonGrouped(%):未分组的应用程序百分比,即HasGroup = 0
  • AverageNonGrouped(%):它是分组应用程序的平均值,即(Invidual NonGrouped(%) / total NonGrouped(%))*100。 ABC的例子是(75/ 165)*100 = 45.45,类似于XYZ,它是(50/ 165)*100 = 30.30。此处16575+50+40
  • 的总和

我的查询如下:

SELECT 
AppName, 
SUM( CASE HasGroup  WHEN 1 THEN 1 ELSE 0 END ) AS Grouped,
SUM( CASE HasGroup WHEN 0 THEN 1 ELSE 0 END ) AS NonGrouped,
ROUND(((SUM( CASE HasGroup  WHEN 1 THEN 1 ELSE 0 END ) / 
    (SUM( CASE HasGroup  WHEN 0 THEN 1 ELSE 0 END ) + 
        SUM( CASE HasGroup WHEN 1 THEN 1 ELSE 0 END )))*100), 2) AS GroupedPercentage,
ROUND(((SUM( CASE HasGroup  WHEN 0 THEN 1 ELSE 0 END ) / 
    (SUM( CASE HasGroup  WHEN 0 THEN 1 ELSE 0 END ) + 
        SUM( CASE HasGroup WHEN 1 THEN 1 ELSE 0 END )))*100), 2) AS NonGroupedPercentage
FROM
    Apps
    INNER JOIN Store
        ON (Apps.Store = Store.Store) 
        AND AppName !='' GROUP BY AppName 

我能够找到除AverageNonGrouped(%)以外的列,因为我不知道如何获得总NonGrouped(%),有谁可以帮我这个

1 个答案:

答案 0 :(得分:1)

这是一个很大的查询,但它完成了工作(我已经在一个数据集上进行了测试)

SELECT 
    AppName, 
    SUM( CASE HasGroup  WHEN 1 THEN 1 ELSE 0 END ) AS Grouped,
    SUM( CASE HasGroup WHEN 0 THEN 1 ELSE 0 END ) AS NonGrouped,
    ROUND(((SUM( CASE HasGroup  WHEN 1 THEN 1 ELSE 0 END ) / 
    (SUM( CASE HasGroup  WHEN 0 THEN 1 ELSE 0 END ) + 
        SUM( CASE HasGroup WHEN 1 THEN 1 ELSE 0 END )))*100), 2) AS GroupedPercentage,
    ROUND(((SUM( CASE HasGroup  WHEN 0 THEN 1 ELSE 0 END ) / 
    (SUM( CASE HasGroup  WHEN 0 THEN 1 ELSE 0 END ) + 
        SUM( CASE HasGroup WHEN 1 THEN 1 ELSE 0 END )))*100), 2) AS NonGroupedPercentage,

    ROUND(((SUM( CASE HasGroup  WHEN 0 THEN 1 ELSE 0 END ) / 
    (SUM( CASE HasGroup  WHEN 0 THEN 1 ELSE 0 END ) + 
        SUM( CASE HasGroup WHEN 1 THEN 1 ELSE 0 END )))*100), 2) / 

    (SELECT SUM(NonGroupedPercentage)
    FROM (
    SELECT 
        ROUND(((SUM( CASE HasGroup  WHEN 0 THEN 1 ELSE 0 END ) / 
            (SUM( CASE HasGroup  WHEN 0 THEN 1 ELSE 0 END ) + 
                SUM( CASE HasGroup WHEN 1 THEN 1 ELSE 0 END )))*100), 2) AS NonGroupedPercentage
    FROM
        apps
    INNER JOIN store
            ON (apps.Store = store.Store) 
            AND AppName !='' 
    GROUP BY AppName 
    ) AS total) *100  AS AverageNonGroupedPercentage
FROM
    apps
INNER JOIN store
    ON (apps.Store = store.Store) 
    AND AppName !='' 
GROUP BY AppName