创建一个视图以显示集合的平均值

时间:2010-12-17 14:34:14

标签: mysql

我有一张桌子,

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的lang-credits百分比的视图,例如

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

我设法做了一个查询,但mysql不会让我从中查看

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。有没有办法写这个让它看起来友好?

2 个答案:

答案 0 :(得分: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)    

答案 1 :(得分: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