2017-05-16 6 views
0

Ich habe eine Tabelle (Tabelle1) mit Datetime-Spalte, die mehrere Male pro Tag speichert.Wie Abfrage Datetime Spalte - MS SQL 2008

zum Beispiel:

select * from table1 
+----+------+------+-----------------+ 
| id | col1 | col2 | datetime  | 
+----+------+------+-----------------+ 
| 1 | A | B | 2016-01-01 16:50| 
+----+------+------+-----------------+ 
| 2 | A | B | 2016-01-01 17:20| 
+----+------+------+-----------------+ 
| 3 | A | B | 2016-01-02 19:50| 
+----+------+------+-----------------+ 
| 4 | A | B | 2016-01-02 20:00| 
+----+------+------+-----------------+ 

Was ich brauche, ist eine Abfrage, oder irgendeine Art von Lösung, die maximale Zeit pro Tag wählen.

gewünschte Ausgabe:

+----+------+------+-----------------+ 
| id | col1 | col2 | datetime  | 
+----+------+------+-----------------+ 
| 2 | A | B | 2016-01-01 17:20| 
+----+------+------+-----------------+ 
| 4 | A | B | 2016-01-02 20:00| 
+----+------+------+-----------------+ 

Antwort

1

Try this:

declare @test table(id int,col1 varchar (10),col2 varchar(10),[datetime] datetime) 


insert into @test values (1,'A' , 'B' ,'2016-01-01 16:50') 
insert into @test values (2,'A' , 'B' ,'2016-01-01 17:20') 
insert into @test values (3,'A' , 'B' ,'2016-01-02 19:50') 
insert into @test values (4,'A' , 'B' ,'2016-01-02 20:00') 

select a.id,r.col1,r.col2,r.maxdate from 
(select col1,col2,max(datetime) as maxdate from @test group by col1,col2,day([datetime])) r 
inner join @test a 
on r.col1=a.col1 and r.col2=a.col2 and r.maxdate=a.datetime 
+0

Inner Join + Gruppe von macht den Trick, danke Ihnen allen für den Beitrag. –

0
SELECT t.id, t.col1,t.col2, r.Maxdate 
FROM (
     SELECT id, MAX(datetime) as Maxdate 
     FROM Yourtable 
     GROUP BY id 
) r 
INNER JOIN Yourtable t 
ON t.id = r.id AND t.datetime = r.Maxdate 
0

Sie müssen Group By Klausel verwenden und SQL Join Ihr gewünschtes Ergebnis zu erzielen.

SELECT tbl.* 
FROM Table tbl 
JOIN 
    (SELECT col1, 
      col2, 
      max(colDateTime) AS DateTimeColumn 
    FROM Table 
    GROUP BY col1, 
      col2, 
      day(colDateTime)) groupTbl ON tbl.colDateTime = groupTbl.DateTimeColumn