2016-06-13 57 views
0

我有1900個位置,我試圖找到訂單的最大日期。以及相關位置/日期的訂單成本和訂單數量。SQL Server - Max有關多條記錄和相關數據的日期

如何構建子查詢或連接以檢索此數據。

舉例如下嘗試:

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 

我敢肯定,我的邏輯是關閉的加我得到了「關於謂語運營商的每一邊的元素數量不匹配」的錯誤。可能是因爲我在主查詢中需要更多的列,而不是我在查詢子查詢中。

任何指導表示讚賞。

+0

? – Backtrack

+0

@Backtrack標題和標籤表明是的,除非OP非常困惑,我敢肯定這不是真的:-) –

+0

你可以爲每個表格添加一些樣例記錄,並且您希望樣品返回的輸出結果? –

回答

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 

如果您正在使用MSSQL,您可以您使用MSSQL使用CTE

+0

對不起,我正在使用SQL Server。更具體地說,我正在通過SSIS包構建數據流任務。 –

+0

我想查看|商店1 | 6/13/2016 | $ 200 | 245 ....正在定位|商店最大日期下訂單|訂單成本|訂單數量 –

+0

@rashaad_hannah,新增訂單。它會給你結果 – Backtrack

相關問題