Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum column to show total in every row

I have a query that looks like this:

select Group, Sum(columnA) as SumColumn
FROM table
GROUP BY Group

I get results looking like this

+-----+---------+
|Group|SumColumn|
+-----+---------+
|A    |10       |
+-----+---------+
|B    |20       |
+-----+---------+

How can I change/add to this to show something like this?

+-----+---------+-----------+
|Group|SumColumn|TotalColumn|
+-----+---------+-----------+
|A    |10       |30         |
+-----+---------+-----------+
|B    |20       |30         |
+-----+---------+-----------+
like image 771
wondergoat77 Avatar asked Jan 16 '14 16:01

wondergoat77


4 Answers

It is hard to see what your data looks like -- but from what you posted this is what you want:

SELECT Name, 
       SumColumn,
       SUM(SumColumn) AS TotalColumn
FROM
(
    SELECT Group as Name, SUM(columnA) AS SumColumn
    FROM Table 
    GROUP BY Group
) T

You might want this -- depending on other stuff.

SELECT *,  
       SUM(columnA) OVER (PARTITION BY Group ORDER BY Group) AS SumColumn,
       SUM(columnA) OVER (PARTITION BY Group) AS TotalColumn
FROM TABLE
like image 76
Hogan Avatar answered Oct 24 '22 02:10

Hogan


Use a sub-query:

SELECT [Group], Sum(columnA) as SumColumn, 
       TotalColumn = (SELECT SUM(columnA) FROM dbo.Table1)
FROM dbo.Table1
GROUP BY [Group]

Demo

like image 30
Tim Schmelter Avatar answered Oct 24 '22 01:10

Tim Schmelter


You can actually mix window functions and aggregation functions in a select statement. So, you can do this without subqueries:

select Group, Sum(columnA) as SumColumn,
       sum(sum(columnA)) over () as TotalColumns
FROM table
GROUP BY Group;
like image 39
Gordon Linoff Avatar answered Oct 24 '22 01:10

Gordon Linoff


Though this may not be the most effective way to do it. Here is my answer.

SELECT a.*,
    (select Sum(columnA)
     FROM table) as [TotalColumn]
FROM (select Group, Sum(columnA) as SumColumn
      FROM table
      GROUP BY Group) as a
like image 21
user2989408 Avatar answered Oct 24 '22 03:10

user2989408