[英]Mysql join rows with same values
Table Scores 表分数
ID SCORE Year_1 Year_2 Year_3 ID SCORE Year_1 Year_2 Year_3
1 ---- A ------ 1 ------ 0 ------ 0 1 ---- A ------ 1 ------ 0 ------ 0
1 ---- C ------ 0 ------ 0 ------ 1 1 ---- C ------ 0 ------ 0 ------ 1
2 ---- B ------ 1 ------ 1 ------ 0 2 ---- B ------ 1 ------ 1 ------ 0
2 ---- B ------ 0 ------ 0 ------ 1 2 ---- B ------ 0 ------ 0 ------ 1
First I want to join the rows on ID when the score is the same, so that in the example below ID 2 has one row. 首先,当分数相同时,我想加入ID上的行,因此在下面的示例中ID 2有一行。
ID SCORE Year_1 Year_2 Year_3 ID SCORE Year_1 Year_2 Year_3
1 ---- A ------ 1 ------ 0 ------ 0 1 ---- A ------ 1 ------ 0 ------ 0
1 ---- C ------ 0 ------ 0 ------ 1 1 ---- C ------ 0 ------ 0 ------ 1
2 ---- B ------ 1 ------ 1 ------ 1 2 ---- B ------ 1 ------ 1 ------ 1
But is it also possible to remove the score column and put the score in the different year-columns as below? 但是,是否也可以删除分数列并将分数放在以下不同的年列中?
ID Year_1 Year_2 Year_3 ID Year_1 Year_2 Year_3
1 ---- A ------ 0 ------ C 1 ---- A ------ 0 ------ C
2 ---- B ------ B ------ B 2 ---- B ------ B ------ B
========================================================================= ================================================== =======================
one problem I have after using the command in the answer, I loose scores. 我在答案中使用命令后遇到的一个问题是,我的成绩不及格。 When the table is like this and there are multiple scores in one year: 当表格是这样并且一年中有多个分数时:
ID SCORE Year_1 Year_2 Year_3 ID SCORE Year_1 Year_2 Year_3
1 ---- A ------ 1 ------ 0 ------ 0 1 ---- A ------ 1 ------ 0 ------ 0
1 ---- B ------ 1 ------ 0 ------ 0 1 ---- B ------ 1 ------ 0 ------ 0
1 ---- C ------ 0 ------ 0 ------ 1 1 ---- C ------ 0 ------ 0 ------ 1
2 ---- B ------ 1 ------ 1 ------ 0 2 ---- B ------ 1 ------ 1 ------ 0
2 ---- B ------ 0 ------ 0 ------ 1 2 ---- B ------ 0 ------ 0 ------ 1
I won't get as below, but one score appearing and loose other(s): 我不会得到以下结果,但是出现一个得分并失去了其他得分:
ID Year_1 Year_2 Year_3 ID Year_1 Year_2 Year_3
1 ---- A,B ---- 0 ------ C 1 ---- A,B ---- 0 ------ C
2 ---- B ------ B ------ B 2 ---- B ------ B ------ B
try this 尝试这个
SELECT id
,score
,Max(year_1) year_1
,Max(year_2) year_2
,Max(year_3) year_3
FROM scores
GROUP BY id,score
and the second one : 第二个:
SELECT id
,group_concat(year_1) year_1
,group_concat(year_2) year_2
,group_concat(year_3) year_3
FROM (
SELECT id
, CASE WHEN Max(year_1)=1 THEN Max(score) END AS year_1
, CASE WHEN Max(year_2)=1 THEN Max(score) END AS year_2
, CASE WHEN Max(year_3)=1 THEN Max(score) END AS year_3
FROM scores
GROUP BY id ,score
) as tbl2
GROUP BY id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.