2017-12-07 20 views
0

2つのテーブルがあり、2番目のテーブルの2番目のフィールドが最大値である2番目のテーブルのすべての最初のテーブルとフィールドを含むクエリを作成する必要があります値。アクセスネストされた選択クエリは最大値の行を取得

Table1 
MatID | MatCode | Name | 
----------------------- 
1  | A  | Ex1 | 
2  | B  | Ex2 | 
3  | C  | Ex3 | 

Table 2 
MatID | MatCode | OtherName | Count | 
------------------------------------ 
1  | A  | Red  | 5  | 
1  | A  | Blue  | 15 | 
1  | A  | Green  | 2  | 
2  | B  | Red  | 25 | 
2  | B  | Blue  | 3  | 
2  | B  | Green  | 1  | 
3  | C  | Red  | 2  | 
3  | C  | Blue  | 3  | 
3  | C  | Green  | 11 | 

結果が

MatID | MatCode | Name | OtherName | 
----------------------------------- 
1  | A  | Ex1 | Blue 
2  | B  | Ex2 | Red 
3  | C  | Ex3 | Green 

だろうが、これは明らかであると思います。アドバンス

+1

あなただけではなく、両方に比べて、最初のテーブルに 'MatCode'を格納する必要がありますテーブル。これはあなたの質問とは関係ありません。データをモデル化するための提案にすぎません。 –

+0

ありがとう、あなたは正しいです。実際のテーブルはもっと複雑で、そのテーブルは1つしかありません。 – Spionred

答えて

0

おかげで、私は相関サブクエリを示唆している:

select t1.*, 
     (select top 1 t2.OtherName 
     from table2 as t2 
     where t2.MatId = t1.MatId 
     order by count desc, matid -- to prevent duplicates 
     ) as OtherName 
from table1 as t1; 
0

試してみてください。

SELECT Z.MatID, Z.MatCode, Z.Name, C.OtherName 
FROM 
(SELECT A.MatID, A.MatCode, A.Name, MAX(Count) as Max_Count 
FROM 
Table1 A INNER JOIN table2 B 
ON A.MatID = B.MatID AND A.MatCode = B.MatCode 
GROUP BY A.MatID, A.MatCode, A.Name) Z 
INNER JOIN Table2 C 
ON Z.MatID = C.MatID AND Z.MatCode = C.MatCode AND Z.Max_Count = C.Count; 
関連する問題