[英]How can I fetch the entire row with the max value in a column of a query with a nested select?
[英]Access nested Select query get the a row with a max value
我有两个表,需要创建一个查询,该查询列出所有第一个表和第二个表中的一个字段,其中第二个表中的第二个字段是最大值。
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
希望这很清楚。
提前致谢
我建议一个相关的子查询:
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;
尝试:
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.