2016-12-13 44 views
0

我需要選擇每天有max(batchid)的行。如何在SQL Server中按日期從表中選擇多個最大行

樣品表:

Id | BatchId |Date     |KeyValue 
-- | --------|---------------------|----------- 
1 | 1  | 2016-12-13 12:30:66 |1234 
2 | 1  | 2016-12-13 12:30:66 |5654 
3 | 2  | 2016-12-13 08:30:66 |1234 
4 | 2  | 2016-12-13 08:30:66 |5654 
5 | 1  | 2016-12-12 12:10:45 |1234 
6 | 1  | 2016-12-12 12:10:45 |5634 
7 | 2  | 2016-12-12 08:10:45 |1234 
8 | 2  | 2016-12-12 08:10:45 |5634 
9 | 3  | 2016-12-12 04:10:45 |9628 

預期輸出:

Id | BatchId |Date     |KeyValue 
-- | --------|---------------------|----------- 
3 | 2  | 2016-12-13 08:30:66 |1234 
4 | 2  | 2016-12-13 08:30:66 |5654 
9 | 3  | 2016-12-12 04:10:45 |9628 

提前感謝!

+0

你說的每一天,然後你的輸出有兩個2016-12-13?你也應該告訴我們你到目前爲止嘗試過什麼...... – Anand

+0

@SqlZim它確實...... 2016-12-13'中的兩行有batchId = 2,只有一行的最大bacthId = 3對於'2016- 12-12' –

+1

歡迎來到StackOverflow!檢查[問]提出問題的提示。在這種情況下,@Anand說,最好提供一些你已經嘗試過的代碼,因爲這是一個問答網站,而不是代碼對我的服務。 – Kateract

回答

0

使用max() over . . .

select t.* 
from (select t.*, max(date) over (partition by cast(date as date)) as maxdate 
     from sample t 
    ) t 
where maxdate = date; 

或者,rank()/dense_rank()

select t.* 
from (select t.*, 
      dense_rank() over (partition by cast(date as date) order by date desc) as seqnum 
     from sample t 
    ) t 
where seqnum = 1; 
+0

Sql Server允許'cast(date as date)'? –

0

校正和戈登·利諾夫的擴張:

rextester:http://rextester.com/GECAZ46515

create table BatchKeys (Id int,BatchId int,Date datetime,KeyValue int) 
insert into BatchKeys (Id,BatchId,Date,KeyValue) values 
(1,1,'2016-12-13T12:30:06',1234) 
,(2,1,'2016-12-13T12:30:06',5654) 
,(3,2,'2016-12-13T08:30:06',1234) 
,(4,2,'2016-12-13T08:30:06',5654) 
,(5,1,'2016-12-12T12:10:45',1234) 
,(6,1,'2016-12-12T12:10:45',5634) 
,(7,2,'2016-12-12T08:10:45',1234) 
,(8,2,'2016-12-12T08:10:45',5634) 
,(9,3,'2016-12-12T04:10:45',9628) 


select t.* 
from (select t.*, max(BatchId) over (partition by cast(date as date)) as maxBatchId 
     from BatchKeys t 
    ) t 
where maxBatchId = BatchId; 

select t.* 
from (select t.*, 
      dense_rank() over (partition by cast(date as date) order by BatchId desc) as seqnum 
     from BatchKeys t 
    ) t 
where seqnum = 1; 

select top 1 with ties t.* 
from BatchKeys t 
order by dense_rank() over (partition by cast(date as date) order by BatchId desc) 
相關問題