COUNT和Group By MYSQL之后的SUM

时间:2015-09-30 10:04:25

标签: mysql sql

我想问一下mysql中的SQL。我堆叠超过1小时:(
我有sql:

    SELECT TZL.IsMissed, COUNT(TZL.ChatID) as Amount FROM tblLog TZL group by TZL.IsMissed

结果:

| IsMissed | Amount |
|        0 |    100 |
|        1 |    500 |

我想在Amount列之后再添加一列,假设新列的名称是 SumAmount
我希望 SumAmount 值为 SUM 金额列。

| IsMissed |金额| SumAmount |
| 0 | 100 | 600 |
| 1 | 500 | 600 |

我已经尝试过如下的SQL:

SELECT
    tbl.*,SUM(tbl.Amount) as SumAmount
FROM
    (
        SELECT
            TZL.IsMissed,
            COUNT(TZL.ChatID) AS Amount
        FROM
            tblLog TZL
        GROUP BY
            TZL.IsMissed
    ) tbl
GROUP BY
tbl.IsMissed 
WITH ROLLUP

但是使用 ROLLUP ,结果会添加一行,而不是列。谁能教我这个? 谢谢你的回答

1 个答案:

答案 0 :(得分:2)

有几种方法可以解决这个问题。我会计算from子句中的值:

SELECT TZL.IsMissed, COUNT(TZL.ChatID) as Amount, tt.SumAmount
FROM tblLog TZL CROSS JOIN
     (SELECT COUNT(*) as SumAmount FROM tblLog) tt
GROUP BY TZL.IsMissed, tt.SumAmount;