SQL SELECT使用3个表

时间:2016-05-06 03:52:43

标签: sql

3个表:TasksProjectsStatuschanges

以下查询正常工作:

select 
    p.projecttypename, p.projectname,
    t.country, t.taskid,
    sc.username, sc.comment, sc.fromstatus, 
    sc.status as tostatus, sc.status as nextstatus 
from 
    iris_RPROD_CPP_R2.TASKS t,
    iris_RPROD_CPP_R2.Projects p,
    iris_RPROD_CPP_R2.statuschanges sc 
where 
    sc.Incorrectlyrouted= 'True'   
order by 
    statuschangeid

但是我想要与t.taskid一样的相同信息,如:

select 
    p.projecttypename, p.projectname,
    t.country, count(t.taskid),
    sc.username, sc.comment, 
    sc.fromstatus, sc.status as tostatus, sc.status as nextstatus 
from 
    iris_RPROD_CPP_R2.TASKS t,
    iris_RPROD_CPP_R2.Projects p,
    iris_RPROD_CPP_R2.statuschanges sc 
where 
    sc.Incorrectlyrouted= 'True'   
order by 
    statuschangeid

我怎么能得到这个?

1 个答案:

答案 0 :(得分:0)

添加计数(taskid)并将其分组如下:

我添加了COUNT(t.taskid) AS Expr1

您还可以更改Expr1您想要提供的名称TaskId

SELECT        p.projecttypename, p.projectname, t.country, t.taskid, sc.username, 
              sc.comment, sc.fromstatus, sc.status AS tostatus, sc.status AS nextstatus, 
              COUNT(t.taskid) AS Expr1
FROM          TASKS AS t CROSS JOIN
                         Projects AS p CROSS JOIN
                         statuschanges AS sc
WHERE        (sc.Incorrectlyrouted = 'True')
GROUP BY p.projecttypename, p.projectname, t.country, t.taskid, sc.username, sc.comment, 
         sc.fromstatus, sc.status, sc.statuschangeid
ORDER BY sc.statuschangeid