2016-06-13 10 views
0

Ich habe 1900 Standorte, die ich versuche, das Maximum (Datum) zu finden, dass eine Bestellung platziert wurde. Und auch die Bestellkosten und die Bestellmenge für den entsprechenden Ort/Datum.SQL Server - Max. Datum für mehrere Datensätze und zugehörige Daten

Wie erstelle ich eine Unterabfrage oder einen Join, um diese Daten abzurufen.

Beispiel Versuch unter:

select table1.location, table2.ord_dt, table2.order_cost, table2.order_qty 
    from table2 
    join table 3 on table2.id1 = table3.id1 
    join table 1 on table1.id1 = table3.id2 
    where table2.ord_dt = (
    select table1.location, max(table2.ord_dt) 
    from table2 
    join table 3 on table2.id1 = table3.id1 
    join table 1 on table1.id1 = table3.id2 
    group by table1.location 

Ich bin sicher, dass meine Logik ist weg und ich bin immer eine „Anzahl der Elemente auf jeder Seite eines Prädikats Operator nicht überein“ Fehler. Wahrscheinlich, weil ich in meiner Hauptabfrage mehr Spalten benötige als in meiner Unterabfrage.

Jede Anleitung wird geschätzt.

+0

verwenden Sie MSSQL verwenden? – Backtrack

+0

@Backtrack Der Titel und das Tag zeigen ja an, außer das OP ist sehr verwirrt, was sicher nicht wahr ist :-) –

+0

Können Sie einige Beispieldatensätze für jede Tabelle und die Ausgabe hinzufügen, die Sie erwarten, dass das Beispiel zurückkehrt? –

Antwort

0
;with cte(location, odate) as 
(

    select table1.location, max(table2.ord_dt) 
    from table2 
    join table 3 on table2.id1 = table3.id1 
    join table 1 on table1.id1 = table3.id2 
    group by table1.location 
) 
select table1.location, table2.ord_dt, table2.order_cost, table2.order_qty 
    from table2 
    join table 3 on table2.id1 = table3.id1 
    join table 1 on table1.id1 = table3.id2 
    join cte on cte.location = table1.location and cte.odate = table2.ord_dt 
order by 
table1.location, table2.ord_dt, table2.order_cost, table2.order_qty 

wenn Sie MSSQL verwenden, können Sie CTE

+0

Entschuldigung, ich benutze SQL Server. Genauer gesagt baue ich eine Datenflussaufgabe über das SSIS-Paket auf. –

+0

Ich möchte sehen | speichern 1 | 13.06.2016 | $ 200 | 245 .... Ort sein maximales Datum, an dem das Geschäft eine Bestellung aufgegeben hat | Bestellkosten | Bestellmenge –

+0

@rashaad_hannah, Bestellung von. Es wird Ihnen das Ergebnis geben – Backtrack

Verwandte Themen