使用连接的列总和

时间:2017-12-14 06:43:18

标签: mysql sql sum average

SELECT
  td.EstimatedTotalAmount_Car,
  AVG(tdca.EstimatedTotalAmount) AS policy_saving
FROM Company_Reporting td
INNER JOIN Company_Car_Archive tdca
  ON tdca.VehClassSize = td.VehClassSize_Car
  AND tdca.VendorName != td.VendorName_Car
  AND tdca.USER_SEARCH_ID = td.SEARCH_ID_Car
WHERE td.Company_id = 12
AND td.CHECKOUT_STS = 1
AND td.Check_Type = 3
AND td.policy_violate_flag = 0
GROUP BY td.ID

以上SQL返回以下输出。

EstimatedTotalAmount_Car    policy_saving
55.86                       75.197856
55.86                       75.197856
170.83                      244.070000
143.66                      132.120000
171.96                      131.007272
222.66                      226.162725
97.03                       79.554001
56.61                       74.213999

但我希望单个记录中两列的总和。

sum(EstimatedTotalAmount_Car): 974.47   sum(policy_saving):1037.523709

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:1)

您可以在外部查询中执行此操作,例如

select sum(EstimatedTotalAmount_Car),
sum(policy_saving)
from(
    /** your query */
) t

答案 1 :(得分:1)

只需打包当前查询并对两列进行求和:

SELECT
    SUM(EstimatedTotalAmount_Car) AS grand_total,
    SUM(policy_saving) AS sum_policy_saving
FROM
(
    SELECT
        td.EstimatedTotalAmount_Car, 
        AVG(tdca.EstimatedTotalAmount) AS policy_saving 
    FROM Company_Reporting td 
    INNER JOIN Company_Car_Archive tdca 
        ON tdca.VehClassSize = td.VehClassSize_Car AND
           tdca.VendorName != td.VendorName_Car AND
           tdca.USER_SEARCH_ID = td.SEARCH_ID_Car
    WHERE
        td.Company_id = 12  AND 
        td.CHECKOUT_STS = 1 AND
        tgd.Check_Type = 3 AND
        td.policy_violate_flag = 0
    GROUP BY td.ID
) t;