如何在这么多的表中构建(activerecord)查询?

时间:2012-08-17 01:34:26

标签: sql ruby-on-rails activerecord

project有很多taskstask可由许多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 最后 任务?输出报告预计为:

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;')

更新:(对于Deefours的评论):这是我为了计算 最后 任务而做的事情(但不知道如何获得 By < / strong>专栏):

{{1}}

4 个答案:

答案 0 :(得分: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

让我知道它是否无法正常工作,因为我现在无法运行它。

答案 1 :(得分:0)

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

P1    T2
P2    T3
P3    T3

然后通过proyect和任务过滤原始表与此查询产生的表,过滤子查询中Proyect IS NOT NULL的记录,并通过subquery.task,originalTable.User获取count(*)组

修改

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

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

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

然后,您必须再次将此表与Tasktable连接,以使用户和组获得计数

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

答案 2 :(得分: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;

答案 3 :(得分: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