如何在mysql中合并列的值

时间:2013-10-16 07:41:22

标签: mysql group-by

让我们考虑一下这个问题

select class_id,case when event_id=2 then sum(time_spent) end as timespent ,case when event_id=3 then sum(timespent) end as visitedtimespent from class group by class_id,event_id;

输出看起来像

class_id     timespent visitedtimespent

1             2000       NULL
1             NULL        10
2             4000       NULL
2             NULL        5

当我使用此查询时

select class_id,case when event_id=2 then sum(time_spent) end as timespent ,case when event_id=3 then sum(time_spent) end as timespent from class group by class_id;

输出看起来像

class_id     timespent visitedtimespent

1             2000       NULL
2             4000       NULL

但我期待这个输出

class_id     timespent visitedtimespent

1             2000        10
2             4000         5

我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:0)

select class_id,
       sum(case when event_id=2 then time_spent else 0 end) as timespent, 
       sum(case when event_id=3 then time_spent else 0 end) as visitedtimespent
from class 
group by class_id

答案 1 :(得分:0)

总结一下。

    select class_id,
sum(case when event_id=2 then time_spent end) as timespent ,
sum(case when event_id=3 then time_spent end) as visitedtimespent
from class group by class_id;

解释差异: case when id... then sum(value)相当于

select case when id then value from
(
    select id, sum(value) as value from table
)subquery 

这是非法分组(ID未汇总或包含在分组中,因此ID值将在所有现有条目之间随机选择),并且您的ID信息将丢失。如果您然后将案例应用于ID信息,则不会得到相关结果。