的Oracle SQL:选择单行多列之间的最晚日期 [英] Oracle SQL: Selecting a single row with the latest date between multiple columns

查看:165
本文介绍了的Oracle SQL:选择单行多列之间的最晚日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的基本表的结构是这样的:




CREATE TABLE EXAMPLE_TABLE

{

ID编号NOT NULL,

- 在这里等栏目,

CREATE_USER VARCHAR2(255字节)NOT NULL,

CREATE_DATE日期DEFAULT SYSDATE NOT NULL ,

UPDATE_USER VARCHAR2(255字节),

UPDATE_DATE日期

}



我想要做的就是选择该行的最高UPDATE_DATE或CREATE_DATE的ID。因此,像这样(虽然这并不奏效 - PID被定义为一个存储过程中的出变量):




选择ID,MAX(GREATEST (CREATE_DATE,UPDATE_DATE)作为LAST_MODIFIED

从EXAMPLE_TABLE

RETURNING ID写入PID;



这将返回本质上就是在表中修改的最后一排的一个ID。一点帮助?

这是Oracle11g的。我目前使用

PS合并到UPSERT行到表,并使用此方法来获取最后upserted行的id,如果你有这样的任何建设性的批评(可能与替代解决方案),我所有的耳朵。我读过很多争论去两种方式,为什么这是一个好/坏的。我会打电话给在C#此过程中,因此,任何其他提示存在表示赞赏。


解决方案

我想你想的结构是这样的:



 选择ID 
(SELECT ID
从EXAMPLE_TABLE
为了通过GREATEST(CREATE_DATE,UPDATE_DATE)说明

,其中的rownum = 1

不过,我想这是可能的日期之一为NULL。如果是这样的:

 从选择ID 
(SELECT ID
由聚结EXAMPLE_TABLE
秩序(GREATEST(CREATE_DATE,UPDATE_DATE),CREATE_DATE)说明

,其中的rownum = 1

这些查询由两个值中较大的每一行上订购,并选择最大值。


My base table structure looks like this:

CREATE TABLE EXAMPLE_TABLE
{
ID NUMBER NOT NULL,
-- Other columns here,
CREATE_USER VARCHAR2(255 BYTE) NOT NULL,
CREATE_DATE DATE DEFAULT SYSDATE NOT NULL,
UPDATE_USER VARCHAR2(255 BYTE),
UPDATE_DATE DATE
}

What I want to do is select the id of the row with the highest update_date or create_date. So something like this (although this doesn't work - pID is defined as an out variable in a stored procedure):

SELECT ID, MAX(GREATEST(CREATE_DATE, UPDATE_DATE) as LAST_MODIFIED
FROM EXAMPLE_TABLE
RETURNING ID INTO pID;

This would return a single id of essentially the last row that was modified in the table. Little help?

P.S. This is in Oracle11g. I'm currently using MERGE to upsert rows into tables, and using this method to get the id of the last upserted row. If you have any constructive criticism of this (potentially with an alternative solution), I'm all ears. I've read plenty of arguments going both ways as to why this is good / bad. I'm going to call this procedure in c#, so any other tips there is appreciated.

解决方案

I think the structure you want is this:

select id
from (SELECT ID
      FROM EXAMPLE_TABLE
      order by GREATEST(CREATE_DATE, UPDATE_DATE) desc
     )
where rownum = 1

However, I suppose it is possible for one of the dates to be NULL. If so:

select id
from (SELECT ID
      FROM EXAMPLE_TABLE
      order by coalesce(GREATEST(CREATE_DATE, UPDATE_DATE), CREATE_DATE) desc
     )
where rownum = 1

These queries are ordering by the larger of the two values on each row, and then selecting the maximum value.

这篇关于的Oracle SQL:选择单行多列之间的最晚日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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