0

This is my table:

  project_id | task_id | foo | bar | job_id |
  -----------+---------+-----+-----+--------+
      1           12      x     y       13
      1           12      x     z       14
      1           12      a     b       15
      1         1210      x     y     1211
      1         1210      z     v     1212 
      1         1220     aa    bb     1221

I trying to write a query where group by by task_id and count job_id per task_id

So I expect something like that:

project_id | task_id | foo | bar | job_id | countJobsperTask |
-----------+---------+-----+-----+--------+------------------+
    1             12      x    y      13          3
    1             12      x    z      14          3        
    1             12      a    b      15          3
    2             1210    x    y      1211        2
    2             1210    z    v      1212        2
    3             1220    aa   bb     1221        1

My not very successful query :

select 
    project_id, task_id, foo, bar, job_id, 
    count(job_id) as "countJobsperTask" 
from
    project 
group by 
    project_id, task_id, job_id
1
  • Based on your test data, each of your groups contains exactly one row, as specified by your GROUP BY terms. If you want to select the original rows (ungrouped), but calculate an aggregate OVER some similar rows, you can use window functions, as shown by @Pooya's answer. There are also several ways to use GROUP BY in a separate expression and then refer to that in your select list. There is a question about how you want to count job_id (distinct or not). That would need to be specified. Commented Nov 14, 2021 at 13:41

1 Answer 1

1

I don't understand why project_id is different between your sample data and expected data, but this query maybe helps you:

demo

select 
  project_id, 
  task_id, 
  foo, 
  bar, 
  job_id, 
  count(job_id) over (partition by project_id, task_id)
from project
Sign up to request clarification or add additional context in comments.

1 Comment

you understood correctly there are still different projects

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.