2017-01-17 22 views
1

我有如下表:TSQL - 獲取,他們的標題是不是空的最新行

======================== 
Id  SubCode Title 
======================== 
1  1  test1 
1  2  test2 
1  3  NULL 
1  4  NULL 
2  1  k1 
2  2  k2 
2  3  k3 
2  4  NULL 

不,我想選擇最新行,他們的標題是不是null,例如用於標識1然後查詢必須顯示test2和標識2它必須是k3

======================== 
Id  SubCode Title 
======================== 
1  2  test2 
2  3  k3 

我寫了這個查詢:

select t.Id, t.SubCode, t.Title from Test t 
inner join (
    select max(Id) as Id, max(SubCode) as SubCode 
    from Test 
    group by Id 
) tm on t.Id = tm.Id and t.SubCode = tm.SubCode 

但這代碼給出錯誤的結果:

======================== 
Id  SubCode Title 
======================== 
1  4  NULL 
2  4  NULL 

任何想法?

+1

所以'SubCode'確定記錄的年齡? –

+0

@TimSchmelter否,'Id'和'SubCode'都是密鑰 –

+2

我沒有要求密鑰,我問過你是如何確定哪個記錄是「較舊」的,因爲你「想要選擇最新的行」?你應該使用'datetime'-column- –

回答

2

你忘了通過寫適當WHERE條款(where title is not null)排除空值。

但是這樣的問題(以獲得最好的/最後的/ ...記錄)通常是最好的解析函數(RANKDENSE_RANKROW_NUMBER)無論如何解決,因爲他們可以訪問的表只有一次:

select id, subcode, title 
from 
(
    select id, subcode, title, rank() over (partition by id order by subcode desc) as rn 
    from test 
    where title is not null 
) ranked 
where rn = 1; 
2

你需要一個Title is not null where子句中你內心的選擇:

select t.Id, t.SubCode, t.Title from Test t 
inner join (
    select max(Id) as Id, max(SubCode) as SubCode 
    from Test 
    where Title is not null 
    group by Id 
) tm on t.Id = tm.Id and t.SubCode = tm.SubCode 
+0

我不知道爲什麼我不考慮'where子句:)) –

相關問題