2016-06-13 12 views
0

注文があった最大(日付)を検索しようとしている1900の場所があります。また、関連するロケーション/日付の注文コストと注文数量も表示されます。SQL Server - 複数のレコードと関連データの最大日付

このデータを取得するために、サブクエリまたは結合を作成するにはどうすればよいですか。以下

例の試み:

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

関連する問題