0

使用以下数据,如何编写 SQL 服务器查询以仅获取下面标有“X”的记录?基本上,我想要每组相似记录的 MAX 日期记录。下面有两组;第一个只有 KEY1 中的数据,第二个在 KEY1 和 KEY2 中都有数据。我尝试使用 OVER 语句,但可以得到我需要的东西。谢谢。

日期-----KEY1-----KEY2

01-Jan......abc.............NULL

02-Jan......def............NULL 'X'

2 月 12 日......abc............123

2 月 14 日......abc............456 'X'

所以这里是用更现实的数据集对问题进行重新措辞。

行日期率 Key1 Key2 Key3

1 01-1 月 150 12345  
2 05-1月155 12345     
3 160 年 1 月 1 日 12345 J100
4 07-2月 170 12345 J100
5 170 年 1 月 9 日 12345 K200
6 150 年 1 月 14 日 12345 J100 ABC
7 175 年 1 月 23 日 12345 J100 ABC

我想要获得的行是 2、4、5 和 7,因为它们各自代表三个键列的每个唯一组合的最大日期。希望这更有意义。谢谢。

4

2 回答 2

0
select distinct LAST_VALUE(date) over (partition by key1, key2, key3 order by date) date,
                LAST_VALUE(rate) over (partition by key1, key2, key3 order by date) rate,
                LAST_VALUE(key1) over (partition by key1, key2, key3 order by date) key1,
                LAST_VALUE(key2) over (partition by key1, key2, key3 order by date) key2,
                LAST_VALUE(key3) over (partition by key1, key2, key3 order by date) key3
from t1

但请注意,这仅适用于 SQL Server 2012。

在其他版本上

  select t1.* 
    from t1, (select key1, key2, key3, max(date) date from t1 group by key1, key2, key3)) t2
where t2.key1 = t1.key1 and t2.key2 = t1.key2 and t2.key3 = t1.key3 and t2.date = t1.date
于 2013-10-24T00:01:04.480 回答
0

这很丑陋,但它确实对我有用。

select r.rate, t1.* from tRate r
join (select max(r.date) date, r.key1, r.key2, r.key3 from tRate r
join (select distinct key1+key2+key3 newKey from tRate) t2 on r.key1+r.key2+r.key3 = t2.newKey group by r.key1, r.key2, r.key3) t1
on r.date = t1.date and r.key1 = t1.key1 and r.key2 = t1.key2 and r.key3 = t1.key3

于 2013-10-24T20:02:31.440 回答