1

我有下表

RecordID     Group     Date        Value
----------------------------------------
 1           Test 1   1/01/2012     10
 2           Test 1   1/01/2012     10
 3           Test 1   1/01/2012     20
 4           Test 2   1/01/2012     20
 5           Test 1   2/01/2012     10
 6           Test 2   2/01/2012     30
 7           Test 1   2/01/2012     20
 8           Test 1   2/01/2012     20
 9           Test 2   2/01/2012     20
10           Test 1   3/01/2012     10
11           Test 2   3/01/2012     10
12           Test 2   3/01/2012     20
13           Test 3   3/01/2012     10
14           Test 1   4/01/2012     10

我需要获取所有 RecordIds,其中对于同一日期和同一组,它具有最低值,并忽略同一日期和同一组具有更大价值的所有记录。所以我的查询需要按“日期”和“组”分组并找到具有最低值的记录,即结果应该是:

RecordIds:1、2、4、5、9、10、11、13、14

4

1 回答 1

7

您可以在子查询中使用排名。

select T.RecordID,
       T.[Group],
       T.Date,
       T.Value
from 
  (
    select RecordID,
           [Group],
           Date,
           Value,
           rank() over(partition by [Group], Date order by Value) as rn
    from YourTable
  ) as T
where T.rn = 1
order by T.RecordID

SQL小提琴

于 2012-10-08T05:27:26.613 回答