2010-12-17 63 views
1

我有一個表,顯示平均,創建視圖在一組

tbl_courses 
------------ 
int id //pk 
int id_formation //fk 
int credits 
enum lang // en, fr, etc 

該表中的數據看起來像這樣

id | id_formation | credits | lang 
1 | 101 | 4 | en 
2 | 101 | 6 | en 
3 | 101 | 5 | fr 
4 | 102 | 8 | en 
5 | 102 | 2 | fr 
6 | 103 | 3 | fr 

我想有一個觀點,即顯示的百分比郎學分每個id_formation,像

id_formation | en_percent | fr_percent 
101 | 66 | 33 
102 | 80 | 20 
103 | 0 | 100 

我設法讓查詢要做到這一點,但MySQL不會讓我MAK E中的觀點出來的

SELECT 
a.id_formation, 
en_percent 
//fr_percent 
FROM tbl_courses a 
JOIN (
    SELECT 
    a.id_formation, 
    FORMAT(SUM(a.credits)*100/b.total,0) AS 'en_percent' 
    FROM tbl_courses a 
    LEFT JOIN (
    SELECT id_formation, SUM(credits) as total 
    FROM tbl_courses 
    GROUP BY id_formation) AS b ON b.id_formation = a.id_formation 
    GROUP BY a.id_formation, a.lang HAVING a.lang='en' 
) AS en ON en.id_formation=a.id_formation 
//repeat join code and switch en to fr 
GROUP BY id_formation 

我重複碼在JOIN得到fr_percent。有沒有辦法寫這個讓它看起來很友善?

+0

你能用主鍵一起發佈tbl_courses結構的相關部分?另外,有多少種語言? – Ronnis 2010-12-17 14:40:28

+0

目前只是英文和法文 – Matt 2010-12-17 14:47:59

回答

1

我用三種語言創建一個小測試用例。看看最後一個查詢。它會給你你需要的東西嗎?如果是這樣,我可以幫你創建你想要的視圖。

create table tbl_courses as 
    select 1 as id_formation, 'en' as lang, 25 as credits union all 
    select 1 as id_formation, 'fr' as lang, 50 as credits union all 
    select 1 as id_formation, 'sv' as lang, 25 as credits union all 
    select 2 as id_formation, 'en' as lang, 80 as credits union all 
    select 2 as id_formation, 'fr' as lang, 15 as credits union all 
    select 2 as id_formation, 'sv' as lang, 5 as credits; 

alter table tbl_courses add primary key(id_formation, lang); 

select id_formation 
     ,count(*)  as num_languages 
     ,sum(credits) as total_credits 
     ,sum(case when lang = 'en' then credits else 0 end) as en_creds 
     ,sum(case when lang = 'fr' then credits else 0 end) as fr_creds 
    from tbl_courses 
group 
    by id_formation; 

+--------------+---------------+---------------+----------+----------+ 
| id_formation | num_languages | total_credits | en_creds | fr_creds | 
+--------------+---------------+---------------+----------+----------+ 
|   1 |    3 |   100 |  25 |  50 | 
|   2 |    3 |   100 |  80 |  15 | 
+--------------+---------------+---------------+----------+----------+ 
2 rows in set (0.00 sec)  
+0

我不認爲這適合我。我爲我的問題添加了一個我正在處理的數據示例。 – Matt 2010-12-17 15:52:27

0

由於Ronnis,關鍵是總和(當情況):

SELECT 
    id_formation, 
    FORMAT(sum(case when lang = 'en' then credits else 0 end)*100/SUM(credits),0) as en_percent, 
    FORMAT(sum(case when lang = 'fr' then credits else 0 end)*100/SUM(credits),0) as fr_percent 
FROM 
    tbl_courses 
GROUP BY id_formation