tags:

views:

85

answers:

6

I want a resultset for this table :

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

Is it possible to get the sum of two colums as another column/ as output in mysql?

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

(Edit: Didn't originally notice it was the total total in the last column.)

Matt S
+3  A: 

To get cross-tab totals (horizontal and vertical):

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

This will give you:

   id     p     u   p_and_u
-----   ---   ---   -------
    1   100    21       121
    2    23    34        57
99999   123    55       178
paxdiablo
@pax: That's quite an interesting query, but I have a feeling that's not what the OP is looking for.
Daniel Vassallo
Which is why I asked for clarification in the question comments. It makes little sense to have the _entire_ total on each row since it's not an attribute of the key (ID).
paxdiablo
@pax: I agree...
Daniel Vassallo
@paxdiablo, thank you very much, I was not expecting this result but this might be what I want.
JPro
+1  A: 
SELECT  id, number_of_posts, number_of_user,
        (
        SELECT  SUM(number_of_posts + number_of_user)
        FROM    mytable
        )
FROM    mytable
Quassnoi
That gives you the total for the whole table on each row, which I don't think is what they wanted.
Dave Costa
@Dave: Actually, I think that's what the OP wants
Daniel Vassallo
@Dave: could you please look at the sample recordset the @op provided before downvoting?
Quassnoi
A: 

Does MySQL support 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)

Edit: based on a quick search, in MySQL the last line might be GROUP BY id WITH ROLLUP.

Dave Costa
This will return the third sum record-wise, not table-wise.
Quassnoi
+2  A: 

You're complicating your query needlessly and using more memory that you have to. Pull the records in one query, then make another query to get the aggregates.

I know it doesn't answer your question, but it's what you should be doing instead. =)

joebert