我有一個表,顯示平均,創建視圖在一組
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
。有沒有辦法寫這個讓它看起來很友善?
你能用主鍵一起發佈tbl_courses結構的相關部分?另外,有多少種語言? – Ronnis 2010-12-17 14:40:28
目前只是英文和法文 – Matt 2010-12-17 14:47:59