HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Avoid double query on the same table

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
samethequeryavoiddoubletable

Problem

I have two queries which are doing basically the same thing, but have different grouping, the first query (query 1) is used to populate a chart, and the second to populate a table.

Query 1:

SELECT key_id
       ,sum(salary)
       ,sum(bonus)
       ,created_at
FROM table
WHERE emp_id = 1
GROUP BY key_id, created_at


Query 2:

SELECT key_id
       ,sum(salary)
       ,sum(bonus)
       ,count(*) OVER() AS full_count
FROM table
WHERE emp_id = 1
GROUP BY key_id


I have created a function that returns those two queries in a json format, chart: [...], table: [...]. The problem is that I need to query the same table twice, because of my grouping. Is there any way of dealing with this situations?

Solution

The new 9.5 version has added CUBE, GROUPING SETS and ROLLUP extensions to GROUP BY which can be used for such queries. If you have to do this in previous versions, one way is using a CTE, with something like (note that it's not the same exact output as your query, since I didn't know the type of created_at. I guess it's a timestamp and didn't want to mix it with the integer count):

WITH grp AS
  ( SELECT key_id,
           sum(salary) AS salary,
           sum(bonus)  AS bonus,
           created_at,
           count(*)    AS full_count
    FROM table
    WHERE emp_id = 1
    GROUP BY key_id, created_at
  )
SELECT *
FROM grp

UNION ALL

SELECT key_id, 
       sum(salary),
       sum(bonus), 
       NULL,
       sum(full_count)   
FROM grp
GROUP BY key_id 

ORDER BY key_id, created_at NULLS LAST;

Code Snippets

WITH grp AS
  ( SELECT key_id,
           sum(salary) AS salary,
           sum(bonus)  AS bonus,
           created_at,
           count(*)    AS full_count
    FROM table
    WHERE emp_id = 1
    GROUP BY key_id, created_at
  )
SELECT *
FROM grp

UNION ALL

SELECT key_id, 
       sum(salary),
       sum(bonus), 
       NULL,
       sum(full_count)   
FROM grp
GROUP BY key_id 

ORDER BY key_id, created_at NULLS LAST;

Context

StackExchange Database Administrators Q#127221, answer score: 4

Revisions (0)

No revisions yet.