2

Aproject有很多tasks。Atask可以由多个 之一处理users。例如:

Project    Task      By
-------  --------  ------
  P1        T1       U1
            T2       U2
  P2        T1       U3
            T2       U4
            T3       U5
  P3        T1       U1
            T2       U3
            T3       U5
  P4        T1       U1
            T2       U3

如何查询用户处理的项目count of中的最后一个任务?输出报告预计为:

  Task   By   Count
  ----  ----  -----
   T2    U2     1
   T2    U3     1
   T3    U5     2

更新:(对于 Deefours 的评论):这是我为计算最后一项任务所做的工作(但不确定如何获取By列):

self.find_by_sql('select task_id, count(task_id) as "count"
from (
        select task_id
        from (
                select * from tasks order by created_at desc
             )
        tasks_sorted 
        group by project_id
     )
latest_tasks 
group by task_id;')
4

4 回答 4

1

这是您要查找的查询:

SELECT t.task_id, u.user_id, count(*) as "count"
FROM project p
INNER JOIN (
    SELECT project_id, MAX(created_at) as "created_at" FROM task GROUP BY project_id
) last_task ON p.project_id=last_task.project_id
INNER JOIN task t ON t.created_at=last_task.created_at
INNER JOIN users u ON t.user_id=u.user_id
GROUP BY t.task_id, u.user_id

让我知道它是否不起作用,因为我现在无法运行它。

于 2012-08-24T14:34:51.547 回答
0

尝试首先进行查询以获取每个项目中的最后一个任务以获得这样的结果集

P1    T2
P2    T3
P3    T3

然后通过proyect将原始表与该查询产生的表左连接,任务过滤子查询中Proyect不为NULL的记录,并通过subquery.task,originalTable.User获取count(*)组

编辑

我假设 TASK 列中的数字是项目中任务的顺序(如果你在表中存储这个 'T1'、'T2'... 值,你应该考虑将它们更改为 int 值)

此查询将获取每个项目的最后一个任务

SELECT project, 
'T' + CAST(MAX(CAST(REPLACE(task, 'T','') AS INT)) AS VARCHAR(3)) AS MaxTask
FROM Tasks
GROUP BY project

然后你必须再次将这个表与任务表加入,以获取用户和组来获取计数

SELECT mt.MaxTask, t.User, count(*) Count
FROM Tasks t LEFT JOIN (
    SELECT project, 
    'T' + CAST(MAX(CAST(REPLACE(task, 'T','') AS INT)) AS VARCHAR(3)) AS MaxTask
    FROM Tasks
    GROUP BY project
) AS mt ON t.project = mt.project AND t.task = mt.task
WHERE mt.task IS NOT NULL
GROUP BY mt.MaxTask, t.User
于 2012-08-17T02:10:19.677 回答
0
 select task_id, user_id, count(user_id) as "count" from (
   select task_id, user_id from (
     select * from (
        select * from tasks order by tasks.created_at desc
     ) last_tasks group by project_id
   ) tasks_by_users INNER JOIN users ON tasks.task_id = tasks_users.task_id
 ) workload group by task_id, user_id;
于 2012-08-21T06:20:44.087 回答
0

使用以下查询:

SELECT P.task_id, P.user_id, count(*) as "count"
FROM project p
INNER JOIN task t ON t.task_id = p.task_id
INNER JOIN (SELECT project_id, MAX(created_at) FROM task GROUP BY project_id) l 
            ON  l.project_id = p.project_id
            AND l.created_at = t.created_at
GROUP BY P.task_id, P.user_id
于 2012-08-25T05:27:25.747 回答