繁体   English   中英

查询以获取最新记录并获得更高的值

[英]Query to get the most recent record and with the higher value

我有这个数据样本:

card  service       date       value
  1      1       27-10-2014      5
  1      1       28-10-2014      5
  1      1       28-10-2014      6

什么是返回最后一行(最近的,并且在出现平局的情况下,较高的值)的最佳方法?

提前致谢。

编辑:

 card  service       date       value
   1      1       27-10-2014      5
   1      1       28-10-2014      5
   1      1       28-10-2014      6
   2      2       29-10-2014      7

这应该已经返回了第三和第四记录。

感谢所有的答复。 但是今天我有一个小的更改请求。 我将有一列带有百分比的列,另一列包含一个字符,以表明是值还是百分比。

我正在尝试做这样的事情:

 select  card,
                         service,
                         max(date),
                         case when type = 'v'
                         then
                         MAX(value) KEEP (
                            dense_rank first order by date desc
                        )
                         else 
                         max(percentage) valor keep (
                           dense_rank first order by date desc
                         ) end   
                 from table
                 group by card,
                 service;

但是我得到的是ORA-00979:不是GROUP BY表达式

因此,您想要具有最新日期和最高值的行吗?

如果您使用的是12.1及更高版本,则可以先使用访存。 按日期和值降序排序并获得一行:

create table t (
  card int, service int, dt date, val int
);

insert into t values (1, 1, date'2014-10-27', 5);
insert into t values (1, 1, date'2014-10-28', 5);
insert into t values (1, 1, date'2014-10-28', 6);

select * from t
order  by dt desc, val desc
fetch first 1 row only;

CARD   SERVICE   DT                     VAL   
     1         1 28-OCT-2014 00:00:00       6 

在11.2和更早版本上,您需要一个子查询,在其中分配一个按日期和值排序的行号:

with ranked as (
  select t.*,
         row_number() over (order by dt desc, val desc) rn
  from   t
)
  select * from ranked
  where  rn = 1;

CARD   SERVICE   DT                     VAL   RN   
     1         1 28-OCT-2014 00:00:00       6    1 

一种好方法是使用KEEP..DENSE_RANKFIRST聚合函数。

SELECT card
    ,service
    ,MAX(date_t)
    ,MAX(value) KEEP (
        DENSE_RANK FIRST ORDER BY date_t DESC
        ) AS value
FROM yourtable
GROUP BY card
    ,service;

演示版

尝试这个:

select *
from (
  select x.*
  from <tablename> x
  where date = (select max(date) from <tablename> )
  order by value desc
) where rownum<2 ;

试试这个查询:-

    SELECT TOP 1 * FROM tableName ORDER BY dateCol1 DESC,valueCol2 DESC;

MySQL中的简单解决方案,

    select * from demo_table t
    where value = (select max(value) from demo_table)
    order by date desc limit 1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM