我有两个表,需要创建一个列出所有第一个表的查询和一个第二个表中的字段,其中第二个表中的第二个字段是最大值。
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
希望这很清楚。
先谢谢
答案 0 :(得分: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;
答案 1 :(得分: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;