组合多个子行

时间:2015-10-01 09:43:41

标签: mysql

在此先感谢,我似乎无法得到它!

我有两张桌子

类别

Id  Name
1   Aptitude
2   English

标记

UserId  CategoryId   Mark
  1        1          25
  1        2          45
  2        1          34
  3        2          45
  4        1          56
  4        2          66

我想要输出的是mysql查询就是这种效果

输出

UserId  AptitudeMark   EnglishMark
  1        25            45
  4        56            66

由于我是mysql的新手,我只能获得一个类别或另一个类别,我也无法将它们放在同一行中。此外,当用户同时拥有类别标记时,我们应该考虑。

5 个答案:

答案 0 :(得分:2)

SELECT main.`id`,A.mark as AptitudeMark,E.mark as EnglishMark FROM `Mark` as main
LEFT JOIN (SELECT id,mark FROM `Mark` WHERE `CategoryId` = 1) as  A ON main.id = A.id
LEFT JOIN (SELECT id,mark FROM `Mark` WHERE `CategoryId` = 2) as  E ON main.id = E.id
GROUP BY main.id

答案 1 :(得分:1)

您可以使用GROUP_CONCAT,但结果会略有不同。看看这个:

SELECT `UserId`, GROUP_CONCAT(`CategoryId`), GROUP_CONCAT(`Mark`) FROM `marks`
GROUP BY `UserID`

答案 2 :(得分:1)

如果CASE(s)的数量是固定的,我们可以使用以下带GROUP BY表达式和category子句的查询来实现此目的。

<强>查询

select * from
(
    select UserId,
    max(case when CategoryId = 1 then Mark else null end) as AptitudeMark,
    max(case when CategoryId = 2 then Mark else null end) as EnglishMark
    from Mark
    group by UserId
)t
where t.AptitudeMark is not null
and t.EnglishMark is not null;

答案 3 :(得分:1)

如果类别未知,那么您将需要使用动态sql,查询看起来像

select ID,count(ID) as `count`
from tableName
group by ID;

这是一个测试用例

set @sql = null;
select
  group_concat(distinct
    concat(
      'max(case when m.CategoryId = ''',
     m.CategoryId,
      ''' then m.Mark end) AS ',
      concat(c.Name,'Mark')
    )
  ) into @sql
from Mark m join Category c on c.Id = m.CategoryId ;

set @sql = concat('select m.UserId, ', @sql, ' from Mark m
                  join Category c on c.Id = m.CategoryId
                  group by m.UserId
');

prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;

运行以上查询将提供

mysql> select * from Category ;
+------+----------+
| Id   | Name     |
+------+----------+
|    1 | Aptitude |
|    2 | English  |
+------+----------+
2 rows in set (0.00 sec)

mysql> select * from Mark ;
+--------+------------+------+
| UserId | CategoryId | Mark |
+--------+------------+------+
|      1 |          1 |   25 |
|      1 |          2 |   45 |
|      2 |          1 |   34 |
|      3 |          2 |   45 |
|      4 |          1 |   56 |
|      4 |          2 |   66 |
+--------+------------+------+

6 rows in set (0.00 sec)

答案 4 :(得分:0)

尝试此查询

SELECT UserId, GROUP_CONCAT(CategoryId,'-',Mark) AS Category_mark
FROM marks
GROUP BY UserId

这将为您提供像

这样的结果
UserId  Category_mark
  1      1-25,2-45,