sql group by和rows to columns

时间:2012-07-30 19:27:16

标签: mysql sql join group-by

我需要一点sql的帮助。

现在我有一个类似的查询:

   SELECT  q.id, 
           q.approved, 
           up.username, 
           h1.name AS h_name1, 
           h2.name AS h_name2,
           s.title,
           v.points
     FROM  votes v, questionaries q
     JOIN  (heroes h1, heroes h2, skills s)  
       ON  (q.hero1=h1.id AND q.hero2=h2.id AND  q.hero1 = s.hero_id)
     JOIN  user_profiles up 
       ON  q.user_id = up.user_id
    WHERE  s.id = v.skill
      AND  q.approved = 2

这样我得到了下一个数据结构:

id appr username    h1    h2   skill points

32  2  username  hero1  hero2  skill1  42
32  2  username  hero1  hero2  skill2  35
32  2  username  hero1  hero2  skill3  43
32  2  username  hero1  hero2  skill4  23

...
and many rows

但理想的结构是:

id appr username   h1     h2     s1    s2      s3     s4     p1   p2   p3   p4

32  2    username  hero1 hero2 skill1 skill2 skill3 skill4   42   35   43   23

有没有办法像这样转换选择结果?

1 个答案:

答案 0 :(得分:2)

Mysql没有pivot,但它确实有group_concat。我认为以下内容可能满足您的需求:

select id, approved, username, hero1, hero2,
       group_concat(title sep ',') as skills,
       group_concat(cast(points as varchar(255)) sep ',')
from (SELECT  q.id, 
              q.approved, 
              up.username, 
              h1.name AS h_name1, 
              h2.name AS h_name2,
              s.title,
              v.points
        FROM  votes v, questionaries q
        JOIN  (heroes h1, heroes h2, skills s)  
          ON  (q.hero1=h1.id AND q.hero2=h2.id AND  q.hero1 = s.hero_id)
        JOIN  user_profiles up 
          ON  q.user_id = up.user_id
       WHERE  s.id = v.skill
         AND  q.approved = 2
     ) t
group by id, approved, username, hero1, hero2

这会将技能和点放在以逗号分隔的列表中,每个列表都在各自的列中。