2011-01-03 3 views
2

Ich habe zwei Tabellen.TSQL Abfrage zum Abrufen von Zeilendetails einer Tabelle mit dem Höchstwert für eine Spalte

Tabelle 1

Num 
1 
2 
3 

Tabelle 2

Num Date Amount 
1  12/31  30 
1  12/30  31 
1  12/29  20 
2  12/31  100 
2  12/30  90 
3  12/31  12 
4  11/1  1 

Nun sollte mein Ergebnis haben

Num Date Amount 
    1 12/31  30 
    2 12/31  100 
    3 12/31  12 

(für die 'Num' Werte in Tabelle 1, mit table2 verbinden, in dem die Datum ist das neueste)

Ich versuche eine tsql-Abfrage zu schreiben, um dies zu erreichen.

Jede Hilfe wird geschätzt. Dank

+1

Was würde mit Ihren Ergebnissen passieren, wenn die erste Zeile der Tabelle 2 nicht existiert? – Blorgbeard

+1

Suchen Sie mit anderen Worten nach Zeilen mit Datum = (in der Tabelle zuletzt) ​​oder nach Zeilen mit Datum = (zuletzt für diese Zahl)? – Blorgbeard

+0

@Blorgbeard Ich suche nach Zeilen in Tabelle2 wo Datum = neueste für diese Zahl. – nvarchar

Antwort

2

Wenn Sie das jüngste Datum für jede tabelle1 num einzeln wollen:

with maxdates as (
    select T1.num, max(T2.date) as date 
     from table2 T2 
     join table1 T1 
     on T2.num = t1.num 
    group by T1.num 
) 
select t2.num, t2.date, t2.amount 
    from table2 T2 
    join maxdates M 
    on T2.num = M.num 
    and T2.date = M.date 

oder wenn Sie das aktuellste Datum für alle passenden Datensätze in der Tabelle wollen:

with maxdate as (
    select max(T2.date) as date 
     from table2 T2 
     join table1 T1 
     on T2.num = t1.num 
) 
select t2.num, t2.date, t2.amount 
    from table2 T2 
    join table1 T1 
    on T2.num = T1.num 
    join maxdate M 
    on T2.date = M.date 
+0

Danke. Scheint den Trick zu machen – nvarchar

2

Versuchen Sie, diese query:

SELECT b.* 
    FROM Table1 a INNER JOIN 
       (
     SELECT a.*, 
       ROW_NUMBER() OVER(PARTITION BY a.Num ORDER BY Date DESC) rnk 
      FROM Table2 a 
     ) b 
     ON a.Num = b.Num 
     AND rnk = 1 
0

Versuchen Sie, diese

select t2.* from table2 as t2 inner join table1 as t1 on t2.num=t2.num 
inner join 
(
Select t2.num,max(t2.amount) as amount from table2 
group by t2.num 
) as t3 on t2.amount=t3.amount 
0
DECLARE @t1 TABLE(num INT) 
DECLARE @t2 TABLE(num INT, [date] NVARCHAR(5), amount INT) 

INSERT INTO @t1 (num) VALUES (1),(2),(3) 

INSERT INTO @t2 (num,[date],amount) VALUES (1,'12/31',30) 
INSERT INTO @t2 (num,[date],amount) VALUES (1,'12/30',31) 
INSERT INTO @t2 (num,[date],amount) VALUES (1,'12/29',20) 
INSERT INTO @t2 (num,[date],amount) VALUES (2,'12/31',100) 
INSERT INTO @t2 (num,[date],amount) VALUES (2,'12/30',90) 
INSERT INTO @t2 (num,[date],amount) VALUES (3,'12/31',12) 
INSERT INTO @t2 (num,[date],amount) VALUES (4,'11/01',1) 

SELECT t2.num,t2.[date],amount 
FROM @t1 t1 JOIN @t2 t2 ON t1.num = t2.num 
WHERE t2.[date] in (
         SELECT MAX(t3.[date]) 
         FROM @t2 t3 
         WHERE t3.num = t2.num 
        ) 
ORDER BY t2.num 
Verwandte Themen