2013-07-01 210 views
0

我已經在Sybase ASE以下數據Sybase ASE的數據分組

id effectiveDate  lastModificationDate rateValue  
----- ---------------- -------------------- ------------ 
1  20130627   6/27/2013 3:27:09 AM 0    
1  20130627   6/27/2013 4:39:10 AM 2.75   
1  20130627   6/28/2013 3:48:15 AM 0    
1  20130627   6/28/2013 4:36:43 AM 2.75   
1  20130628   6/28/2013 3:48:14 AM 0    
1  20130628   6/28/2013 4:36:42 AM 2.75   
2  20130628   6/28/2013 4:36:42 AM .75   
2  20130628   6/28/2013 3:48:14 AM 0    

我怎麼組,所以,我只得到了最後一排,即我得到它具有最大lastModificationDate爲同一行ID + EFFECTIVEDATE。

所以輸出將是:

id  effectiveDate  lastModificationDate value  
----- ---------------- -------------------- ------------ 
1  20130627   6/28/2013 4:36:43 AM 2.75   
1  20130628   6/28/2013 4:36:42 AM 2.75   
2  20130628   6/28/2013 4:36:42 AM .75   

請注意,這將是對TSQL(Sybase ASE的15)。 編輯:有改變的數據,使之更加逼真

回答

0

嘗試:

SELECT t1.* 
FROM Table1 t1 
WHERE t1.lastModificationDate = (SELECT MAX(t2.lastModificationDate) 
            FROM Table1 t2 
            WHERE t2.effectiveDate = t1.effectiveDate 
            AND t2.id = t1.id) 

Sybase文檔:

子查詢可以嵌套的外 選擇的其中或具有子句中,插入,更新或刪除語句,在另一個子查詢 或選擇列表中。或者,您可以編寫許多語句,將 包含子查詢作爲連接; Adaptive Server將這種語句 作爲連接進行處理。

+0

與Sybase的唯一問題子查詢是可以只有1列。考慮數據如下所示的情況:對另一個id重複相同的lastmodificationdate.Have編輯問題以反映我的評論。 – Achow

+0

好的,現在編輯? – Justin

0

另一個答案避免使用子查詢將是...

select id, effectiveDate, lastModificationDate, rateValue 
from #mydata 
group by id, effectiveDate 
having lastModificationDate = max(lastModificationDate) 

如果我想你的數據存儲在一個#mydata臨時表

create table #mydata(
    id     int  null, 
    effectiveDate  char(8) null, 
    lastModificationDate datetime null, 
    rateValue   money null 
) 

insert into #mydata(id, effectiveDate, lastModificationDate, rateValue) select 1, "20130627", "6/27/2013 3:27:09 AM", 0    
insert into #mydata(id, effectiveDate, lastModificationDate, rateValue) select 1, "20130627", "6/27/2013 4:39:10 AM", 2.75   
insert into #mydata(id, effectiveDate, lastModificationDate, rateValue) select 1, "20130627", "6/28/2013 3:48:15 AM", 0    
insert into #mydata(id, effectiveDate, lastModificationDate, rateValue) select 1, "20130627", "6/28/2013 4:36:43 AM", 2.75   
insert into #mydata(id, effectiveDate, lastModificationDate, rateValue) select 1, "20130628", "6/28/2013 3:48:14 AM", 0    
insert into #mydata(id, effectiveDate, lastModificationDate, rateValue) select 1, "20130628", "6/28/2013 4:36:42 AM", 2.75   
insert into #mydata(id, effectiveDate, lastModificationDate, rateValue) select 2, "20130628", "6/28/2013 4:36:42 AM", .75   
insert into #mydata(id, effectiveDate, lastModificationDate, rateValue) select 2, "20130628", "6/28/2013 3:48:14 AM", 0