将n条记录合并到MySQL中的单条记录中

时间:2015-04-10 06:23:45

标签: mysql

我有以下n条记录:

###Date Rank1 Rank2 Rank3 Rank4 Rank5 Rank6 Rank7  
10-01-2015    1    0    0    0    0    0    0   
10-01-2015    0    1    0    0    0    0    0   
10-01-2015    0    0    1    0    0    0    0   
10-01-2015    0    0    0    1    0    0    0   
10-01-2015    0    0    0    0    1    0    0   
10-01-2015    0    0    0    0    0    1    0   
10-01-2015    0    0    0    0    0    0    1  

我想要的输出是

### Date Rank1 Rank2 Rank3 Rank4 Rank5 Rank6 Rank7  
  10-01-2015    1    1    1    1    1    1    1  

有没有办法实现这个目标?

2 个答案:

答案 0 :(得分:1)

您需要sum()group by

select
Date,
sum(Rank1) as Rank1,
sum(Rank2) as Rank2,
sum(Rank3) as Rank3,
sum(Rank4) as Rank4,
sum(Rank5) as Rank5,
sum(Rank6) as Rank6,
sum(Rank7) as Rank7
from table_name
group by Date

答案 1 :(得分:1)

SELECT Date, sum(Rank1), sum(Rank2), 
             sum(Rank3), sum(Rank4), 
             sum(Rank5), sum(Rank6), 
             sum(Rank7)

FROM YourTable

GROUP BY Date

可以用于上面的例子,但是如果那里有2,你想要什么?毕竟,排名通常从1开始,而不是零。通过将sum()替换为min()来选择每天的峰值等级是微不足道的。