【问题标题】:Access nested Select query get the a row with a max value访问嵌套选择查询获取具有最大值的行
【发布时间】:2017-12-07 00:51:16
【问题描述】:

我有两个表,需要创建一个查询,列出所有第一个表和第二个表中的一个字段,其中第二个表中的第二个字段是最大值。

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

希望这很清楚。

提前致谢

【问题讨论】:

  • 您应该只将MatCode 存储在第一个表中,而不是两个表中。这与您的问题无关;这只是对数据建模的建议。
  • 谢谢,你是对的。真正的表要复杂得多,而且只有一个。

标签: sql ms-access ms-access-2013


【解决方案1】:

我会建议一个相关的子查询:

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;

【讨论】:

    【解决方案2】:

    试试:

    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;
    

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      相关资源
      最近更新 更多