多个联接中的行总和

时间:2018-09-20 17:05:23

标签: mysql join sum

我正在尝试为多个联接求和。我只能在单个表中找到它,我已经使用了以下查询。

SELECT sd.Descrip
    ,0 AS TotalLedgerNumber
    ,ss.Total
FROM tblServiceSummary ss
LEFT JOIN servdesc sd ON ss.Service_time = sd.ServDescID
JOIN funct fn ON fn.FunctID = ss.FunctionID
GROUP BY sd.Descrip

UNION ALL

SELECT 'Total'
    ,SUM(IFNULL(NULL, 0)) AS TotalLedgerNumber
    ,sum(ss.Total)
FROM tblServiceSummary ss
LEFT JOIN servdesc sd ON ss.Service_time = sd.ServDescID
JOIN funct fn ON fn.FunctID = ss.FunctionID
WHERE fn.StartDate BETWEEN "2018-9-18"
        AND "2018-9-18"
GROUP BY sd.Descrip

这给了我这样的结果

enter image description here

我想同时显示以上所有显示行的总和

我试图在上下查询中添加删除组,并在其中添加。如果我尝试从较低..删除组,则显示为Total |空| null,但这不起作用。请建议

1 个答案:

答案 0 :(得分:0)

如果您尝试对Group之后的所有行进行求和,则可以封装查询和SUM。

示例:

SELECT
   SUM(Descrip)
FROM
   (

SELECT sd.Descrip
    ,0 AS TotalLedgerNumber
    ,ss.Total
FROM tblServiceSummary ss
LEFT JOIN servdesc sd ON ss.Service_time = sd.ServDescID
JOIN funct fn ON fn.FunctID = ss.FunctionID
GROUP BY sd.Descrip

UNION ALL

SELECT 'Total'
    ,SUM(IFNULL(NULL, 0)) AS TotalLedgerNumber
    ,sum(ss.Total)
FROM tblServiceSummary ss
LEFT JOIN servdesc sd ON ss.Service_time = sd.ServDescID
JOIN funct fn ON fn.FunctID = ss.FunctionID
WHERE fn.StartDate BETWEEN "2018-9-18"
        AND "2018-9-18"
GROUP BY sd.Descrip

) summedRows