我正在使用以下声明并获得我需要的几乎所有内容。另外,我想获得所有row_total结果的SUM。
SELECT c.id AS campaign_id, c.amount AS campaign_amount, c.warning_trigger,
COUNT(cc.id) as code_count, DATEDIFF(c.end_date, CURDATE()) as days_remain,
SUM(c.amount) as row_total
FROM campaigns c
JOIN campaign_codes cc
LEFT JOIN partners p on p.id = 4
WHERE c.partner_id = 4 AND cc.status = 0 AND c.id = cc.campaign_id
GROUP BY c.id
ORDER BY campaign_amount ASC
这是一个示例结果,最后一列是我想要添加到一起的列:
1 10.00 30 992 24 9920.00
3 25.00 30 995 290 24875.00
16 50.00 30 988 335 49400.00
17 100.00 30 1000 335 100000.00
答案 0 :(得分:11)
获得运行总和:
SELECT c.id AS campaign_id, c.amount AS campaign_amount, c.warning_trigger,
COUNT(cc.id) as code_count, DATEDIFF(c.end_date, CURDATE()) as days_remain,
SUM(c.amount) as row_total, @r := @r + SUM(c.amount) AS running_sum
FROM (
SELECT @r := 0
) vars,
campaign c, …
将总计(以及所有其他聚合)作为附加记录:
SELECT *
FROM (
SELECT c.id AS campaign_id, c.amount AS campaign_amount, c.warning_trigger,
COUNT(cc.id) as code_count, DATEDIFF(c.end_date, CURDATE()) as days_remain,
SUM(c.amount) as row_total
FROM campaign c, …
GROUP BY
c.id WITH ROLLUP
) q
ORDER BY
campaign_amount ASC
要在其他字段中获得总和:
SELECT c.id AS campaign_id, c.amount AS campaign_amount, c.warning_trigger,
COUNT(cc.id) as code_count, DATEDIFF(c.end_date, CURDATE()) as days_remain,
SUM(c.amount) as row_total,
(
SELECT SUM(c.amount)
FROM campaign c, …
-- the same but without the GROUP BY and ORDER BY clauses.
)
FROM campaign c, …
GROUP BY
c.id
ORDER BY
campaign_amount ASC
答案 1 :(得分:4)
封装您的查询,如:
SELECT SUM([row_total]) FROM (
Your query
) Source
从下面的评论中,您可以尝试...
Your Query
UNION ALL
SELECT '', '', '', '', '', SUM([row_total]) FROM (
Your query
) Source
union all允许您在结果集中追加一行,这将为您提供“总行数”。您可以更改空字段(单引号)以匹配您的数据类型,或为它们指定代表总行数的特殊值。
答案 2 :(得分:1)
SELECT TB.campaign_id, TB.campaign_amount, TB.warning_trigger, TB.code_count, TB.days_remain, TB.row_total, SUM(TB.row_total) GlobalTotal FROM (SELECT c.id AS campaign_id, c.amount AS campaign_amount, c.warning_trigger,
COUNT(cc.id) as code_count, DATEDIFF(c.end_date, CURDATE()) as days_remain,
SUM(c.amount) as row_total
FROM campaigns c
JOIN campaign_codes cc
LEFT JOIN partners p on p.id = 4
WHERE c.partner_id = 4 AND cc.status = 0 AND c.id = cc.campaign_id
GROUP BY c.id
ORDER BY campaign_amount ASC) TB
GROUP BY TB.campaign_id, TB.campaign_amount, TB.warning_trigger, TB.code_count, TB.days_remain, TB.row_total