toplanmasıyla iki colums mysql toplam

4 Cevap php

Ben bu tablo için bir resultset istiyorum:

ID  Number_of_posts   Number_of_user
1   100               21
2   23                34

olarak

   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 olarakanother column/ olarakoutput in mysql?

4 Cevap

Cross-tab toplamları (yatay and dikey) almak için:

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

Bu size verecektir:

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

Sen gereksiz yere sorgu zorlaştıran ve gereken daha fazla bellek kullanıyor demektir. Bir sorguda kayıtları çekin, sonra agrega almak için başka bir sorgu yapmak.

Ben sorunuza cevap vermez biliyorum, ama bunun yerine yapıyor olması gereken de budur. =)

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

(Edit: aslında o son sütunda toplam toplam olarak fark etmedi.)

MySQL desteği TOPLAMASI mu?

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: hızlı bir arama dayanarak, MySQL son satırı olabilir GROUP BY id WITH ROLLUP.