简体   繁体   中英

SQL aggregates over 3 tables

Well, this is annoying the hell out of me. Any help would be much appreciated.

I'm trying to get a count of how many project Ids and Steps there are. The relationships are:

  • Projects (n-1) Pages
  • Pages (n-1) Status Steps

Sample Project Data

id  name    
1   est et
2   quia nihil

Sample Pages Data

id  project_id  workflow_step_id    
1   1           1
2   1           1
3   1           2
4   1           1
5   2           3
6   2           3
7   2           4

Sample Steps Data

id  name
1   a
2   b
3   c
4   d

Expected Output

project_id  name  count_steps
1           a     3
1           b     1
2           c     2
2           d     1

Thanks!

An approach to meet the expected result. See it also at SQL Fiddle

CREATE TABLE Pages
    ("id" int, "project_id" int, "workflow_step_id" int)
;

INSERT INTO Pages
    ("id", "project_id", "workflow_step_id")
VALUES
    (1, 1, 1),
    (2, 1, 1),
    (3, 1, 2),
    (4, 1, 1),
    (5, 2, 3),
    (6, 2, 3),
    (7, 2, 4)
;


CREATE TABLE workflow_steps
    ("id" int, "name" varchar(1))
;

INSERT INTO workflow_steps
    ("id", "name")
VALUES
    (1, 'a'),
    (2, 'b'),
    (3, 'c'),
    (4, 'd')
;


CREATE TABLE Projects
    ("id" int, "name" varchar(10))
;

INSERT INTO Projects
    ("id", "name")
VALUES
    (1, 'est et'),
    (2, 'quia nihil')
;

Query 1 :

select pg.project_id, s.name, pg.workflow_step_id, ws.count_steps
from (
      select distinct project_id, workflow_step_id
      from pages ) pg
inner join (
    select workflow_step_id, count(*) count_steps
    from pages 
    group by workflow_step_id
  ) ws on pg.workflow_step_id = ws.workflow_step_id
inner join workflow_steps s on pg.workflow_step_id = s.id
order by project_id, name, workflow_step_id

Results :

| project_id | name | workflow_step_id | count_steps |
|------------|------|------------------|-------------|
|          1 |    a |                1 |           3 |
|          1 |    b |                2 |           1 |
|          2 |    c |                3 |           2 |
|          2 |    d |                4 |           1 |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM