Sorry for this long winded question, but I’m not sure how to go about constructing this SQL query needed for the results I want. I’ll outline the two queries that I currently run and work fine and I will outline the results I need. Any help will be appreciated.
1st Query:
SELECT c.name AS name, count(*) AS total, sum(a.views) AS total_views, sum(a.views) / count(*) as average_views
FROM table_a a
JOIN table_b b ON b.id = a.b_id
JOIN table_c c ON c.id = b.c_id
WHERE a.status = 0 AND a.type in (2, 4, 5)
GROUP BY c.name ORDER BY c.name;
Result:
--------------------------------------------
name | total | total_views | average_views |
--------------------------------------------
aaaa | 2 | 150 | 75 |
bbbb | 1 | 75 | 75 |
dddd | 1 | 25 | 25 |
--------------------------------------------
2nd query:
SELECT c.name AS name, count(*) AS total, sum(a.views) AS total_views, sum(a.views) / count(*) as average_views
FROM table_a a
JOIN table_b b ON b.id = a.b_id
JOIN table_c c ON c.id = b.c_id
WHERE a.status = 0 AND a.type in (1, 3)
GROUP BY c.name ORDER BY c.name;
2nd results:
--------------------------------------------
name | total | total_views | average_views |
--------------------------------------------
aaaa | 2 | 200 | 100 |
bbbb | 1 | 100 | 100 |
dddd | 1 | 25 | 25 |
--------------------------------------------
Given these tables with this data:
Table table_a:
-----------------------------------
id | b_id | views | type | status |
-----------------------------------
1 | 100 | 100 | 2 | 0 |
2 | 200 | 75 | 4 | 0 |
3 | 300 | 50 | 5 | 0 |
4 | 400 | 25 | 2 | 0 |
5 | 500 | 100 | 1 | 0 |
6 | 600 | 100 | 1 | 0 |
7 | 700 | 100 | 3 | 0 |
8 | 800 | 25 | 3 | 0 |
-----------------------------------
Table table_b:
-------------
id | c_id |
-------------
100 | 1000 |
200 | 2000 |
300 | 1000 |
400 | 4000 |
500 | 1000 |
600 | 2000 |
700 | 4000 |
800 | 1000 |
-------------
Table table_c:
-------------
id | name |
-------------
1000 | aaaa |
2000 | bbbb |
3000 | cccc |
4000 | dddd |
-------------
This is the table that I actually want, which is simply a concantenation of the above two tables with the common column being the name column.
-------------------------------------------------------------------------------------------------------------------------------
name | total_type245 | total_views_type245 | average_views_type245 | total_type13 | total_views_type13 | average_views_type13 |
-------------------------------------------------------------------------------------------------------------------------------
aaaa | 2 | 150 | 75 | 2 | 200 | 100 |
bbbb | 1 | 75 | 75 | 1 | 100 | 100 |
dddd | 1 | 25 | 25 | 1 | 25 | 25 |
-------------------------------------------------------------------------------------------------------------------------------
It’s most likely quite a simple query, but I cannot work out how to do it.
Thanks.
Just join the results together;