如何根据类别和日期排除相同ID的行

时间:2014-01-20 10:39:56

标签: sql-server tsql sql-server-2008-r2 inner-join

+--+-------+----------+---+
|ID|OrderID|OrderDate |Cat|
+--+-------+----------+---+
|1 |240904 |23/05/2013|63 |
+--+-------+----------+---+
|1 |338584 |11/12/2013|64 |
+--+-------+----------+---+
|1 |47309  |21/11/2011|64 |
+--+-------+----------+---+
|2 |175307 |23/11/2012|63  |
+--+-------+----------+---+
+--+-------+----------+---+
|2 |195307 |24/12/2012|64  |
+--+-------+----------+---+
+--+-------+----------+---+
|2 |175300 |23/11/2011|63  |
+--+-------+----------+---+
+--+-------+----------+---+
|5 |175307 |23/11/2012|63  |
+--+-------+----------+---+
+--+-------+----------+---+
|5 |215307 |15/1/2013|64  |
+--+-------+----------+---+
+--+-------+----------+---+
|7 |195307 |15/06/2012|63  |
+--+-------+----------+---+

我正在使用SQL Server 2008 R2。我正在尝试(努力)找到一种方法来获取更新的OrderDate Cat 64然后Cat 63来获取相同的ID,这些ID看起来就像{{1}分隔的那些记录一样} 以上。

1 个答案:

答案 0 :(得分:0)

尝试这样

Select OrderID,OrderDate From
(
Select *,ROW_NUMBER() over(PARTITION by ID,CAT Order by OrderDate DESC) AS RN
From tbl
) AS Tmp
Where RN = 1

Working Fiddle