0

I have a table (maintable) of the format:

(id, intcol1, intcol2, intcol3, ...)

Sample data:

123, 582585, 25215718, 15519
234, 2583, 2371, 1841948
345, 42389, 234289, 234242

I want to run some aggregate calculations using outside data to group the data by. The data I have is of the form:

(id, groupcol)

Sample data:

123, "January",
234, "February"
345, "January"

In this case, suppose I want the SUM of intcol1 using the provided groupings to match IDs, the result would be:

"January", 624974               # 42389 + 582585
"February", 2583

My question is: How do I get the "group data" into the query? Using a WITH clause and JOINING it against the maintable? Or adding it to a temporary table and using that in a following query?

I can manipulate the data I have and format it however way is easiest from the program running the SQL query.

What is the best / fastest / simplest method?

Edited for clarity

3
  • @a_horse_with_no_name Done! Commented Jul 11, 2017 at 11:24
  • Where does the 624974 in 624974 + 582585 come from? Commented Jul 11, 2017 at 11:30
  • @a_horse_with_no_name Me working too fast >_< Fixed now Commented Jul 11, 2017 at 12:55

1 Answer 1

2

That looks like a simple join and group by:

select t2.groupcol, 
       sum(t1.intcol1)
from maintable t1 
  join table_2 t2 on t1.id = t2.id
group by t2.groupcol;

If you don't have that "outside" data in a table, you can do something like this:

select t2.groupcol, 
       sum(t1.intcol1)
from maintable t1 
  join (
    values 
      (123, 'January'), 
      (234, 'February'),
      (345, 'January')
  ) as t2 (id, groupcol) on t1.id = t2.id
group by t2.groupcol;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.