使用以下数据,如何编写SQL Server查询以仅获取下面标有“X”的记录?基本上我希望记录具有相似的每组记录的MAX日期。下面有两组;第一个只有KEY1中的数据,第二个在KEY1和KEY2中都有数据。我尝试使用OVER语句,但可以得到我需要的东西。感谢。
DATE ------ ------ KEY1 KEY2
01-JAN ...... ABC .......... NULL
02-Jan ...... def ........... NULL'X'
12 ......二月ABC ......... 123
14-Feb ...... abc ......... 456'X'
所以这里是一个更真实的数据集问题的重新措辞。
Row Date Rate Key1 Key2 Key3 1 01-Jan 150 12345 2 05-Jan 155 12345 3 01-Jan 160 12345 J100 4 07-Feb 170 12345 J100 5 09-Jan 170 12345 K200 6 14-Jan 150 12345 J100 ABC 7 23-Jan 175 12345 J100 ABC
我想要获得的行是2,4,5和7,因为它们分别代表三个关键列的每个唯一组合的最大日期。希望更有意义。感谢。
答案 0 :(得分: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
答案 1 :(得分: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