1

I have a table in Postgres 9.3.6 that looks like this:

utm_source    value
fb            12
fb            8
google        3
google        4
null          5

I want to run a SQL query to sum value by utm_source, but also include the total value as well. So the final table should look like:

utm_source    sum
fb            20
google        7
null          5
all           32

This is what I'd otherwise use:

SELECT SUM(value) as sum FROM my_table GROUP BY utm_source;

But I want the all in there as well!

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
Some Guy
  • 12,768
  • 22
  • 58
  • 86

2 Answers2

1
SELECT isnull(utm_source,'')
       ,SUM(value) as sum 
FROM my_table 
GROUP BY isnull(utm_source,'') with rollup

you can update the NULL to 'all' later.

Vivek S.
  • 19,945
  • 7
  • 68
  • 85
Zee
  • 830
  • 1
  • 9
  • 22
  • The OP did not clarify the RDBMS at first. It's Postgres, `rollup` is a non-standard feature of SQL Server and does not work in Postgres. Details: http://dba.stackexchange.com/questions/94817/grouping-equivalent-in-postgresql/94822#94822 – Erwin Brandstetter Apr 03 '15 at 23:51
1

Using a CTE so the base table is only scanned once, which is typically faster. There is some overhead cost for the CTE, so it may not pay for trivially small tables.

WITH cte AS (
   SELECT utm_source, sum(value) AS sum_value
   FROM   tbl
   GROUP  BY 1
   )
SELECT * FROM cte
UNION ALL  -- not just UNION !
SELECT 'all', sum(sum_value) FROM cte;

SQL Server has a non-standard extension for the task using the grouping() and rollup() keywords. Here is how to implement it in Postgres:

Community
  • 1
  • 1
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228