在mysql中总计两列

时间:2010-05-26 15:22:20

标签: php mysql

我想要这个表的结果集:

ID  Number_of_posts   Number_of_user
1   100               21
2   23                34

as

   ID  Number_of_posts   Number_of_user   Number_of_posts_AND_Number_of_user
    1   100               21               178
    2   23                34               178
-----------------------------------------------
        123                55

是否有可能将两个列的总和作为另一列/作为mysql中的输出?

6 个答案:

答案 0 :(得分:3)

获取交叉表总计(水平垂直):

select id,
       number_of_posts as p,
       number_of_users as u,
       number_of_posts+number_of_users as p_and_u
    from tbl
union all
select 99999 as id,
       sum(number_of_posts) as p,
       sum(number_of_users) as u,
       sum(number_of_posts+number_of_users) as p_and_u
    from tbl
order by 1

这会给你:

   id     p     u   p_and_u
-----   ---   ---   -------
    1   100    21       121
    2    23    34        57
99999   123    55       178

答案 1 :(得分:2)

您不必要地使查询复杂化并使用更多内存。在一个查询中拉出记录,然后进行另一个查询以获取聚合。

我知道它没有回答你的问题,但这是你应该做的事情。 =)

答案 2 :(得分:1)

SELECT  id, number_of_posts, number_of_user,
        (
        SELECT  SUM(number_of_posts + number_of_user)
        FROM    mytable
        )
FROM    mytable

答案 3 :(得分:0)

SELECT SUM(Number_of_posts), SUM(Number_of_user) FROM table;

答案 4 :(得分:0)

SELECT *, 
       (SELECT SUM(Number_of_posts) + SUM(Number_of_user) FROM TABLE) AS total 
FROM table;

(编辑:最初没有注意到它是最后一栏中的总数。)

答案 5 :(得分:-1)

MySQL是否支持ROLLUP?

SELECT id,
       SUM(Number_of_posts) Number_of_posts,
       SUM(Number_of_user) Number_of_user,
       SUM(Number_of_posts) + SUM(Number_of_user) Number_of_posts_AND_Number_of_user
  FROM table
  GROUP BY ROLLUP(id)

编辑:基于快速搜索,在MySQL中最后一行可能是GROUP BY id WITH ROLLUP