1

我有 2 个表:活动和用户。用户有列:名称,活动活动:名称、类型、时间、用户 ID。

例如我有这些表:

users
-----
id | name | active
1  | marc | true
2  | john | true
3  | mary | true
4  | nico | true

activities
-----
id | name | type | time | user_id
1  | morn | walk | 90   | 2
2  | morn | walk | 22   | 2
3  | morn | run  | 12   | 2
4  | sat  | walk | 22   | 1
5  | morn | run  | 13   | 1
6  | mond | walk | 22   | 3
7  | morn | walk | 22   | 2
8  | even | run  | 42   | 1
9  | morn | walk | 22   | 3
10 | morn | walk | 62   | 1
11 | morn | run  | 22   | 3

现在我想得到一个表格,它将总结每种活动所花费的时间,并按用户名对其进行分组。所以:

result
------
user name | type | time
marc      | walk | 84
marc      | run  | 55
john      | walk | 134
john      | run  | 12
mary      | walk | 44
mary      | run  | 2
nico      | walk | 0
nico      | run  | 0

我应该如何编写这个查询来得到这个结果?

提前感谢杰拉德

4

3 回答 3

1
Select u.name, a.type, SUM(a.time) FROM 
activities a
LEFT JOIN users u
ON a.user_id = u.id
GROUP BY u.name, a.type

小提琴

也可以使用它来获得零计数

SELECT c.name,c.type,aa.time FROM
(Select u.id,u.name, b.type  FROM 
users u
CROSS JOIN (SELECT DISTINCT type FROM activities) b) c
LEFT JOIN (SELECT a.user_id, a.type, SUM(a.time) as time FROM
activities a 
GROUP BY a.user_id, a.type) aa ON
aa.user_id = c.id and c.type = aa.type

小提琴2

于 2013-08-27T12:39:08.043 回答
1

您可以使用coalesce为空活动获取 0 并distinct获取所有类型的可能活动

select
   u.name, c.type,
   coalesce(sum(a.time), 0) as time
from (select distinct type from activities) as c
   cross join users as u
   left outer join activities as a on a.user_id = u.id and a.type = c.type
group by u.name, c.type
order by u.name, c.type

sql fiddle demo

于 2013-08-27T14:40:34.950 回答
0

这可能有效:

select users.name,activities.type,sum(activities.time)
from users left join activities on users.id = activities.user_id
where users.active group by users.name,activities.type
于 2013-08-27T12:39:12.770 回答