3

我有下表:

-----------------------------------------------------------
ID     oDate         oName     oItem    oQty    oRemarks
-----------------------------------------------------------
1      2016-01-01    A         001      2       
2      2016-01-01    A         002      1       test
3      2016-01-01    B         001      3  
4      2016-01-02    B         001      2
5      2016-01-02    C         001      2
6      2016-01-03    B         002      1
7      2016-01-03    B         001      4
       ff.

我想获取每个名称的最新记录。所以结果应该是这样的:

-----------------------------------------------------------
oDate         oName     oItem    oQty    oRemarks
-----------------------------------------------------------
2016-01-01    A         001      2       
2016-01-01    A         002      1       test
2016-01-02    C         001      2
2016-01-03    B         002      1
2016-01-03    B         001      4
ff.

有谁知道如何得到这个结果?

4

5 回答 5

6

rankwindow 子句允许您根据某些分区对行进行排名,然后您可以只选择顶部的行:

SELECT oDate, oName, oItem, oQty, oRemarks
FROM   (SELECT oDate, oName, oItem, oQty, oRemarks,
               RANK() OVER (PARTITION BY oName ORDER BY oDate DESC) AS rk
        FROM   my_table) t
WHERE  rk = 1
于 2016-02-05T08:22:40.687 回答
3

这是一个不使用分析功能的通用查询。

SQLFiddle Demo

SELECT a.*
FROM table1 a
INNER JOIN
    (SELECT max(odate) modate,
          oname,
          oItem
   FROM table1
   GROUP BY oName,
            oItem
    ) 
    b ON a.oname=b.oname
AND a.oitem=b.oitem
AND a.odate=b.modate
于 2016-02-05T08:30:19.997 回答
2

我认为您需要这样的查询:

SELECT *
FROM (SELECT *,
        ROW_NUMBER() OVER (PARTITION BY oName ORDER BY oDate DESC) seq
    FROM yourTable) t
WHERE (seq <= 2)
ORDER BY oDate; 
于 2016-02-05T08:20:46.637 回答
2

向表中添加一个primary key假设id字段并使其自动递增。然后订购id你会得到它。这是传统的方式。通过使用您的表,您只能订购oDate。但是有多次相同的日期,所以它也不会解决你的问题。

于 2016-02-05T08:26:59.827 回答
0

您必须ROW_NUMBER在以下情况下使用:

select oDate, oName, oItem, oQty, oRemarks
from (
   select *, row_number() over(partition by oName, oItem order by oDate desc) rn  
   from #t
)x
where rn = 1
order by oDate

输出

oDate   oName   oItem   oQty    oRemarks    
2016-01-01  A   001     2                   
2016-01-01  A   002     1       test        
2016-01-02  C   001     2                   
2016-01-03  B   001     4                   
2016-01-03  B   002     1                   
于 2016-02-05T08:21:43.210 回答