【发布时间】:2014-01-24 09:22:48
【问题描述】:
我有三个表:活动、动作(每个动作是一个活动的一次执行)和照片(每个动作都可以附加照片)。
现在我想按降序检索活动,并且对于每个活动,我想要花费在它上的总时间和附加到它的总照片。使用最后一个动作的停止时间计算的活动顺序。
例如对于以下数据
activities
------------------
_id | title
------------------
1 | Activity 1
2 | Activity 2
3 | Activity 3
4 | Activity 4
actions
-------------------------------------------------------------
_id | activity_id | date_started | date_stopped
-------------------------------------------------------------
1 | 1 | 2014-01-23 20:45:03 | 2014-01-23 20:45:24
2 | 2 | 2014-01-23 20:45:27 | 2014-01-23 20:45:29
3 | 3 | 2014-01-23 20:45:31 | 2014-01-23 20:45:43
4 | 1 | 2014-01-23 20:45:46 | 2014-01-23 20:45:48
5 | 4 | 2014-01-23 20:45:50 | 2014-01-23 20:46:19
photos
--------------------------------------------------------
_id | action_id | date_taken | path
--------------------------------------------------------
1 | 1 | 2014-01-23 20:45:11 | 758712034.jpg
2 | 1 | 2014-01-23 20:45:21 | 537444469.jpg
3 | 3 | 2014-01-23 20:45:39 | 28884579.jpg
4 | 5 | 2014-01-23 20:45:58 | 1519722792.jpg
5 | 5 | 2014-01-23 20:46:08 | 298808374.jpg
6 | 5 | 2014-01-23 20:46:15 | 2059925529.jpg
我希望通过此查询获得所需的数据:
SELECT
activityId, title, sum(seconds) AS totalSeconds, sum(cnt) AS totalPhotos
FROM
(
SELECT
activities._id AS activityId, activities.title AS title,
actions._id AS actionId,
strftime("%s", ifnull(actions.date_stopped, 'now')) -
strftime("%s", actions.date_started) AS seconds,
count(photos._id) AS cnt
FROM
activities JOIN actions ON activities._id = actions.activity_id
LEFT OUTER JOIN photos ON photos.action_id = actions._id
GROUP BY 1,2,3,4
ORDER BY actionId DESC
)
GROUP BY 1
但是,不幸的是,它给出了这样的结果:
activityId | title | totalSeconds | totalPhotos
--------------------------------------------------------
1 | Activity 1 | 23 | 2
2 | Activity 2 | 2 | 0
3 | Activity 3 | 12 | 1
4 | Activity 4 | 29 | 3
我正在努力解决这个问题(请参阅操作表中activity_id 的顺序):
activityId | title | totalSeconds | totalPhotos
--------------------------------------------------------
4 | Activity 4 | 29 | 3
1 | Activity 1 | 23 | 2
3 | Activity 3 | 12 | 1
2 | Activity 2 | 2 | 0
如何更改我的查询以获得我想要的?
【问题讨论】:
标签: sql sqlite join count aggregate-functions