Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select distinct column field and total sum for it in mysql

Tags:

sql

mysql

i have following table:

topic_id(unique)  forum_id   forum_views

1002                1885         5
1003                1893         2
1004                1885         3
1005                1892         6

How can i get output like this: (unique forum_id with total forum views from above table)

forum_id    forum_views
1885           8
1893           2
1892           6

ANY HELP IS APPRECIATED.

This is what i am trying:

select distinct forum_id, sum(topic_views) from table_name

like image 873
daman Avatar asked Nov 27 '12 10:11

daman


People also ask

How do I sum a column of distinct values in SQL?

The SQL Server SUM() function is an aggregate function that calculates the sum of all or distinct values in an expression. In this syntax: ALL instructs the SUM() function to return the sum of all values including duplicates. ALL is used by default.

How do I sum values based on criteria in another column in MySQL?

You can use the SUM() function in a SELECT with JOIN clause to calculate the sum of values in a table based on a condition specified by the values in another table.

How do I find the total of a column in MySQL?

SELECT count(*) AS anyName FROM information_schema. columns WHERE table_name =' yourTableName'; Applying the above syntax in the example table with the name 'NumberOfColumns'. mysql> SELECT count(*) AS NUMBEROFCOLUMNS FROM information_schema.

How do I SELECT distinct columns in MySQL?

To get unique or distinct values of a column in MySQL Table, use the following SQL Query. SELECT DISTINCT(column_name) FROM your_table_name; You can select distinct values for one or more columns. The column names has to be separated with comma.


2 Answers

select forum_id, 
       sum(forum_views) as forum_views
from jforum_topics
group by forum_id
like image 135
juergen d Avatar answered Oct 28 '22 23:10

juergen d


Use this query select forum_id, sum(distinct forum_views) from table group by forum_id;

In this query sum distinct will do the sum of distinct value and do the grouping by the desired column.

If you want sum of all the values irrespective of distinctness then simply use sum(forum_views).

like image 44
Tirtha Maitra Avatar answered Oct 29 '22 00:10

Tirtha Maitra