0

我编写了以下查询以返回具有最新日期的记录。

select fs.company_id, max(fs.create_dt) as latestcreatedate
from field_sale fs 
group by fs.company_id
order by fs.company_id

查询一切正常。但是我需要检索带有所有相关列的记录。例如,id、title、desc 等。

如何检索具有相应列的记录?

4

2 回答 2

2

这样做的几种方法:

-- 1. 
SELECT a.* 
FROM field_sale a 
INNER JOIN 
(
select fs.company_id, max(fs.create_dt) as latestcreatedate
from field_sale fs 
group by fs.company_id   
)b 
ON b.company_id = a.company_id AND b.latestcreatedate = a.create_dt
order by a.company_id;

--  2.  
SELECT b.* FROM 
( 
   SELECT a.* , ROW_NUMBER() 
    OVER (PARTITION BY a.company_id ORDER BY a.create_dt DESC)
    AS rn
   FROM field_sale a 
)b WHERE b.rn  = 1
ORDER BY company_id
于 2013-07-12T15:34:48.033 回答
1
WITH    t AS (
           SELECT   fs.company_id,
                    fs.create_dt AS latestcreatedate,
                    id,
                    title,
                    etc,
                    ROW_NUMBER() OVER ( PARTITION BY fs.company_id ORDER BY fs.create_dt DESC ) AS rowNum
           FROM     field_sale fs
         )
SELECT  t.company_id,
        t.latestcreatedate,
        t.id,
        t.title,
        t.etc
FROM    t
WHERE   t.rowNum = 1
ORDER BY t.company_id
于 2013-07-12T15:36:59.820 回答