0

让我们考虑这个查询

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

我怎样才能做到这一点?

4

2 回答 2

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
于 2013-10-16T07:43:09.500 回答
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 信息,您将不会获得相关结果。

于 2013-10-16T07:44:32.143 回答