SUM一组SUMS

时间:2018-03-28 05:47:11

标签: mysql sql sum

我在代码中创建了两行的SUM,但是已经有了SUMS。我最终得到了一个错误。有人可以帮我代码吗?我想要的计算是SUM(yr_L / yr_CC)。我意识到我不能使用别名来进行计算,但我似乎无法使其工作。

以下工作原理,没有复杂的SUM计算线...

SELECT
IF (Artist LIKE '%Bethel%' , 'Bethel', NULL ) as Artist,
COUNT(IF(CCD > 0,1,NULL)) as "c_CC",
ROUND(SUM(CC28) / COUNT(IF(CCD > 0,1,NULL)) * 13,0) as yr_CC,
COUNT(IF(LD > 0,1,NULL)) as c_L,
ROUND(SUM(L28) / COUNT(IF(LD > 0,1,NULL)) * 13,0) as yr_L,
COUNT(IF(FD > 0,1,NULL)) as c_F,
ROUND(SUM(F28) / COUNT(IF(FD > 0,1,NULL)) * 13,0) as yr_F,
COUNT(IF(MTD > 0,1,NULL)) as c_MT,
ROUND(SUM(MT28) / COUNT(IF(MTD > 0,1,NULL)) * 13,0) as yr_MT,
ROUND(SUM(CC28) / COUNT(IF(CCD > 0,1,NULL)) * 13,0) +
    ROUND(SUM(L28) / COUNT(IF(LD > 0,1,NULL)) * 13,0) +
    ROUND(SUM(MT28) / COUNT(IF(MTD > 0,1,NULL)) * 13,0) +
    ROUND(SUM(CC28) / COUNT(IF(CCD > 0,1,NULL)) * 13,0)
    AS yr_Total
FROM praisecharts_reporting.large_sales_report
GROUP BY 1

以下是我所做的创建错误(我添加的等式周围有空格):

SELECT
IF (Artist LIKE '%Bethel%' , 'Bethel', NULL ) as Artist,
COUNT(IF(CCD > 0,1,NULL)) as "c_CC",
ROUND(SUM(CC28) / COUNT(IF(CCD > 0,1,NULL)) * 13,0) as yr_CC,
COUNT(IF(LD > 0,1,NULL)) as c_L,
ROUND(SUM(L28) / COUNT(IF(LD > 0,1,NULL)) * 13,0) as yr_L,

SUM (
        (
            SUM(L28) / COUNT(IF(LD > 0,1,NULL)) -- yr_L
        ) / 
        (
            SUM(CC28) / COUNT(IF(CCD > 0,1,NULL)) -- yr_CC
        )
    )
    AS r_L_C,

COUNT(IF(FD > 0,1,NULL)) as c_F,
ROUND(SUM(F28) / COUNT(IF(FD > 0,1,NULL)) * 13,0) as yr_F,
COUNT(IF(MTD > 0,1,NULL)) as c_MT,
ROUND(SUM(MT28) / COUNT(IF(MTD > 0,1,NULL)) * 13,0) as yr_MT,
ROUND(SUM(CC28) / COUNT(IF(CCD > 0,1,NULL)) * 13,0) +
    ROUND(SUM(L28) / COUNT(IF(LD > 0,1,NULL)) * 13,0) +
    ROUND(SUM(MT28) / COUNT(IF(MTD > 0,1,NULL)) * 13,0) +
    ROUND(SUM(CC28) / COUNT(IF(CCD > 0,1,NULL)) * 13,0)
    AS yr_Total
FROM praisecharts_reporting.large_sales_report
GROUP BY 1

1 个答案:

答案 0 :(得分:1)

这里最简单的事情可能是重复这两个总和来取得商:

SELECT
    IF (Artist LIKE '%Bethel%' , 'Bethel', NULL) AS Artist,
    COUNT(IF(CCD > 0,1,NULL)) AS "c_CC",
    ROUND(SUM(CC28) / COUNT(IF(CCD > 0,1,NULL)) * 13, 0) AS yr_CC,
    COUNT(IF(LD > 0,1,NULL)) as c_L,
    ROUND(SUM(L28) / COUNT(IF(LD > 0,1,NULL)) * 13,0) as yr_L,
    COUNT(IF(FD > 0,1,NULL)) as c_F,
    ROUND(SUM(F28) / COUNT(IF(FD > 0,1,NULL)) * 13,0) as yr_F,
    COUNT(IF(MTD > 0,1,NULL)) as c_MT,
    ROUND(SUM(MT28) / COUNT(IF(MTD > 0,1,NULL)) * 13,0) as yr_MT,
    ROUND(SUM(CC28) / COUNT(IF(CCD > 0,1,NULL)) * 13,0) +
        ROUND(SUM(L28) / COUNT(IF(LD > 0,1,NULL)) * 13,0) +
        ROUND(SUM(MT28) / COUNT(IF(MTD > 0,1,NULL)) * 13,0) +
        ROUND(SUM(CC28) / COUNT(IF(CCD > 0,1,NULL)) * 13,0) AS yr_Total,
    -- new code here:
    ROUND( (SUM(L28) / COUNT(IF(LD > 0,1,NULL))) /
           (SUM(CC28) / COUNT(IF(CCD > 0,1,NULL))), 0) AS new_column
FROM praisecharts_reporting.large_sales_report
GROUP BY 1;