2013-10-23 44 views
0

使用以下數據,如何編寫SQL服務器查詢以僅獲取下面標有'X'的記錄?基本上我想要記錄的MAX日期是相似的每組記錄。下面有兩組;第一隻在KEY1中有數據,第二隻在KEY1和KEY2中都有數據。我嘗試使用OVER語句,但可以得到我需要的。謝謝。如何通過SQL Server查詢獲取以下數據

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

01月...... ABC .......... NULL

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

12-Feb ...... 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

基本上,你想查詢MAX(日期)和1鍵,右側分組? – Hackerman

+0

一組是在key1中有'abc'的三行 - 另一組是在key1中有'def'的單行? – dav1dsm1th

+0

我不應該使用'abc'作爲KEY1的第四行值,因爲它混淆了這個問題。記錄按照它們是僅包含KEY1中的值還是包含KEY1和KEY2中的值進行分組。所以在這個例子中,記錄1和2是group1,記錄3和4是group 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 

要mindfull不過,這將只工作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 
+0

我已經重寫了問題並添加了更好的數據例。目前上面的查詢沒有找回我需要的數據。 –

+0

我已更改查詢以反映您的要求。訣竅是定義可用於分組的另一個字段。你可以在沒有CTP的情況下通過case語句進行分組,但是這看起來很醜陋和怪異。 –

+0

謝謝,我會試一試,因爲它看起來比我的黑客更優雅。 –

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

相關問題