根据最后日期选择记录 [英] Select records based on last date

查看:105
本文介绍了根据最后日期选择记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于下面称为 Course 的表:





如何选择具有课程名称和最新日期的记录?我的意思是,如果一个ID有两个相同的课程名称,则只应显示最新的课程名称,如下所示。



简单地说,我只想显示最新的行每个( ID,课程名称)。





如果我在课程表中有两个日期列,即StartDate& EndDate和我只想根据EndDate显示相同的内容??



我正在使用PostgreSQL。

解决方案

在PostgreSQL中,要为一组定义的列获取唯一行,首选的技术通常是 DISTINCT ON

 选择DISTINCT ON( ID)* 
从 Course
ORDER BY ID, Course Date DESC NULL LAST , 课程名;

假设您实际上使用了那些不幸的大写标识符和空格。



这样,每个 ID 都会得到一排-已知最新的课程日期 和第一个课程名称 (根据排序顺序),以确保在该日期有联系。



如果您的列定义为 NOT NULL NULLS LAST $ c>。



要获取每个( ID, Course Name)的唯一行::

 选择区分开( ID,课程名称)* 
来自课程
排序依据 ID,课程名称,课程日期 DESC NULLS LAST;

此相关答案的详细信息:




Based on the table called Course below:

How can I select records which have course name with latest date? I mean if I have two same course names for one ID, I should only show the latest one as the below result.

Simply, I want only to show the latest row per ("ID", "Course Name").

And what if I have two date columns in Course table, which are StartDate & EndDate and I want to show the same based on EndDate only.?

I am using PostgreSQL.

解决方案

In PostgreSQL, to get unique rows for a defined set of columns, the preferable technique is generally DISTINCT ON:

SELECT DISTINCT ON ("ID") *
FROM   "Course"
ORDER  BY "ID", "Course Date" DESC NULLS LAST, "Course Name";

Assuming you actually use those unfortunate upper case identifiers with spaces.

You get exactly one row per ID this way - the one with the latest known "Course Date" and the first "Course Name" (according to sort order) in case of ties on the date.

You can drop NULLS LAST if your column is defined NOT NULL.

To get unique rows per ("ID", "Course Name"):

SELECT DISTINCT ON ("ID", "Course Name") *
FROM   "Course"
ORDER  BY "ID", "Course Name", "Course Date" DESC NULLS LAST;

Details in this related answer:

这篇关于根据最后日期选择记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆