MYSQL - 按一列分组并滑动另一列

时间:2015-09-25 10:30:52

标签: mysql pivot-table

我有一个表记录用户发送到不同平台(有3个)的消息。可以将相同的消息发送到多个平台。我希望通过user_id和GROUP BY message_code对表进行排队,每个平台都有自己的列,其中1表示已发送,0表示未发送。

使用MYSQL SELECT队列可以实现吗?

+------------------------------------+
|id |message_code |platform |user_id |
+------------------------------------+
|1  |2wkdeyu      |1        |256     |
|2  |2wkdeyu      |2        |256     |
|3  |4kdi940      |1        |256     |
|4  |3eji903      |2        |256     |
|5  |4kdi940      |2        |256     |
|6  |4kdi940      |3        |256     |
|7  |6eioio4      |1        |256     |
+------------------------------------+

我做了什么。

SELECT message_code,GROUP_CONCAT(platform)AS平台,user_id FROM message_log WHERE user_id ='256'GROUP BY message_code;

+--------------------------------+
|message_code |platform |user_id |
+--------------------------------+
|2wkdeyu      |1,2      |256     |
|4kdi940      |1,2,3    |256     |
|3eji903      |2        |256     |
|6eioio4      |1        |256     |
+--------------------------------+

但我想要完成的是这个。

+----------------------------------------------------------+
|message_code |platform 1 |platform 2 |platform 3 |user_id |
+----------------------------------------------------------+
|2wkdeyu      |1          |1          |0          |256     |
|4kdi940      |1          |1          |1          |256     |
|3eji903      |0          |1          |0          |256     |
|6eioio4      |1          |0          |0          |256     |
+----------------------------------------------------------+

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

试试这个:

org.reflections.ReflectionsException: Scanner SubTypesScanner was not configured
    at org.reflections.Store.get(Store.java:58)
    at org.reflections.Store.get(Store.java:70)
    at org.reflections.Store.getAll(Store.java:97)
    at org.reflections.Reflections.getAllAnnotated(Reflections.java:423)
    at org.reflections.Reflections.getTypesAnnotatedWith(Reflections.java:384)
    at org.reflections.Reflections.getTypesAnnotatedWith(Reflections.java:370)

您可以使用select message_code, coalesce(max(case when platform=1 then 1 end),0) as `platform 1`, coalesce(max(case when platform=2 then 1 end),0) as `platform 2`, coalesce(max(case when platform=3 then 1 end),0) as `platform 3`, user_id from message_log where user_id=256 group by message_code; 检查特定平台。

SQL小提琴示例:http://sqlfiddle.com/#!9/74b1e/3