이 긴 질문에 대해 유감스럽게 생각합니다.하지만 원하는 결과를 얻기 위해 필요한 SQL 쿼리를 작성하는 방법을 모르겠습니다. 현재 실행 중이며 정상적으로 작동하는 두 가지 쿼리를 요약하고 필요한 결과를 간략하게 설명합니다. 어떤 도움을 주시면 감사하겠습니다.결합 된 예상 결과에 대한 SQL 쿼리 - 피벗?
1 조회 :
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;
결과 :
--------------------------------------------
name | total | total_views | average_views |
--------------------------------------------
aaaa | 2 | 150 | 75 |
bbbb | 1 | 75 | 75 |
dddd | 1 | 25 | 25 |
--------------------------------------------
2 쿼리
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;
2 결과 :
--------------------------------------------
name | total | total_views | average_views |
--------------------------------------------
aaaa | 2 | 200 | 100 |
bbbb | 1 | 100 | 100 |
dddd | 1 | 25 | 25 |
--------------------------------------------
이 데이터와이 테이블을 감안할 때 : 표 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_b가 :
이-------------
id | c_id |
-------------
100 | 1000 |
200 | 2000 |
300 | 1000 |
400 | 4000 |
500 | 1000 |
600 | 2000 |
700 | 4000 |
800 | 1000 |
-------------
표 table_c : 이것은 내가 실제로 원하는 테이블을이다
-------------
id | name |
-------------
1000 | aaaa |
2000 | bbbb |
3000 | cccc |
4000 | dddd |
-------------
, 인 위의 두 테이블의 concantenation은 공통 컬럼이 이름 컬럼이됩니다.
-------------------------------------------------------------------------------------------------------------------------------
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 |
-------------------------------------------------------------------------------------------------------------------------------
가장 간단한 쿼리 일 가능성이 높습니다.하지만 어떻게 할 수 있습니까?
감사합니다.
두 쿼리 모두에서 내부 조인을 만들 수 있습니다. –
http://sqlfiddle.com/#!3/aa1d5/2 테스트 여기 – BeNdErR