Mysql按照字段值做分组行转列查询

今天做个后台服务,有个需求是批量生成一批表的数据,如果用BulkInsert会提升很大一截提交效率,但是如果用循环构造提交的Datable,则算法开销太高,所以用这种查询批量查出符合格式的DataTable结果集。

*思想就是将查询列做CASE判断值,然后放在 SELECT段中作为别名列显示字段值,然后再根据ID分组。

下面是内层的原始查询效果:

下面是行转列后查询效果如图:

 

下面是上面两张图的最终查询语句:

 1 SELECT f_gameID,SUM(score) AS totNum,
 2     SUM(CASE f_sub WHEN '01' THEN score ELSE 0 END) AS f_subject01,SUM(CASE f_sub WHEN '02' THEN score ELSE 0 END) AS f_subject02,
 3     SUM(CASE f_sub WHEN '03' THEN score ELSE 0 END) AS f_subject03,SUM(CASE f_sub WHEN '04' THEN score ELSE 0 END) AS f_subject04,
 4     SUM(CASE f_sub WHEN '05' THEN score ELSE 0 END) AS f_subject05,SUM(CASE f_sub WHEN '06' THEN score ELSE 0 END) AS f_subject06,
 5     SUM(CASE f_sub WHEN '07' THEN score ELSE 0 END) AS f_subject07,SUM(CASE f_sub WHEN '08' THEN score ELSE 0 END) AS f_subject08,
 6     SUM(CASE f_sub WHEN '09' THEN score ELSE 0 END) AS f_subject09
 7 FROM 
 8 (
 9     SELECT u.f_gameID,u.f_sub,COUNT(u.f_sub) AS score
10     FROM t_mfg_GameUserAnswers AS u
11     LEFT JOIN t_mfg_Class AS c ON u.f_gameId = c.f_gameId
12     WHERE u.f_startTime > '2015-07-20' 
13     AND u.f_endTime < '2015-07-24'
14     -- AND c.f_schoolId = 193034
15     GROUP BY u.f_gameID ,u.f_sub
16 ) AS a
17 GROUP BY f_gameID;

 

posted @ 2015-07-24 11:01  lichjx  阅读(8177)  评论(0编辑  收藏  举报