如何在sql select语句中为每个id选择最大值?

时间:2014-01-31 18:11:15

标签: mysql select max

考虑这两个表。

第一张表


stageTable

级ID -----艺名

1 -----------开始

2 -----------规划

3 -----------工作

4 -----------评分

5 -----------合


第二张表


stageProject

级ID -------专案编号

1 ------------- 1

2 ------------- 1

3 ------------- 1

4 ------------- 1

1 ------------- 2

2 ------------- 2

3 ------------- 2

4 ------------- 2

5 ------------- 2

1 ------------- 3

2 ------------- 3

3 ------------- 3


我想做的是从每个projectId,我想获得max stageId值

所以我想最终得到:

1-4

2-5

3-3

并从舞台表中分配stageName,以便最终结果为

专案编号----- -----最大艺名

1 4评论

2 5结束

3 3工作

我试过

select a.projectid, max(a.stageid), b.stageName
from stageProject a, stageTable b
where a.stageId=b.stageId
group by a.projectId

但它不起作用

我以正确的stageId和max结束,但stageName始终是相同的

你能救我一下吗?

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

SELECT a.projectId,a.maxStageId,b.stageName
FROM (SELECT projectId,max(stageId) as maxStageId
      FROM stageProject 
      GROUP BY 1 ) a
INNER JOIN stageTable b ON a.maxStageId = b.stageId;

sqlfiddle demo

这将获得每个projectID的最大stageID,然后获取这些结果并使用stageTable进行内部联接以获取其名称。

应该做你想做的事。

答案 1 :(得分:0)

试试这个

select distinct projectid, 
       (select max(stageid) 
        from  stageProject p2
        where p1.projectId = p2.projectId),
       (selec stageName from stageTable 
        where stageId = (select max(stageid) 
                         from stageProject p2
                         where p1.projectId = p2.projectId))
from stageProject p1

或者

select ps.projectid, ps.stageid, st.stagename
from stageTable st, 
      (select a.projectid, max(a.stageid) stageid
       from stageProject a, stageTable b
       where a.stageId=b.stageId
       group by a.projectId) ps
where st.stageid = ps.stageid
相关问题