I have three tables:

我有三个表:

  1. project: project_id, project_name
  2. 项目:project_id project_name
  3. milestone: milestone_id, milestone_name
  4. 里程碑:milestone_id milestone_name
  5. project_milestone: id, project_id, milestone_id, completed_date
  6. project_milestone: id、project_id、milestone_id、completed_date

I want to get the second highest completed_date and milestone_id from project_milestone grouped by project_id. That is I want to get the milestone_id of second highest completed_date for each project. What would be the correct query for this?

我想从project_id分组的project_milestone中获得第二个最高的completed_date和milestone_id。这就是我想要为每个项目获得第二个最高完成日期的里程碑。这个问题的正确查询是什么?

2 个解决方案

#1


7

I think you can do what you want with the project_milestone table and row_number():

我认为您可以使用project_milestone表和row_number()做您想做的事情:

select pm.*
from (select pm.*,
             row_number() over (partition by project_id order by completed_date desc) as seqnum
      from project_milestone pm
      where pm.completed_date is not null
     ) pm
where seqnum = 2;

If you need to include all projects, even those without two milestones, you can use a left join:

如果您需要包含所有项目,即使没有两个里程碑,您可以使用左连接:

select p.project_id, pm.milestone_id, pm.completed_date
from projects p left join
     (select pm.*,
             row_number() over (partition by project_id order by completed_date desc) as seqnum
      from project_milestone pm
      where pm.completed_date is not null
     ) pm
     on p.project_id = pm.project_id and pm.seqnum = 2;

更多相关文章

  1. HSQLDB / Oracle - IN子句中的1000多个项目
  2. 测试Android真机访问电脑主机web项目服务器的问题
  3. 从零开始的Android新项目10 - React Native & Redux
  4. Android Studio如何使用GitHub上的开源项目
  5. 菜鸟窝-仿京东淘宝项目学习笔记(二)ToolBar的基本使用
  6. [置顶] Jenkins构建Android项目持续集成之findbugs的使用
  7. 使用Kotlin开发Android项目-Kibo(二)
  8. 如何把项目从github上导入到android studio上
  9. 直接拿来用!十大Material Design开源项目

随机推荐

  1. 基础概念---mysql 列转行,合并字段
  2. 按平均值优化sql结果集
  3. MySQL数据库离线包安装与注册
  4. 如何使用基于条件的PHP来改变CSS属性?
  5. 如何从mysql表中删除具有相同列值的行?
  6. Linux下使用C/C++访问数据库——SQL Serv
  7. 如何将xml文件转换为mysql?
  8. linux下mysql的root密码忘记,怎么改root密
  9. MySQL SET,ENUM类型数据小结
  10. mysql主从同步报slave_sql_running:no的