SQL Group By with Inner Joins

时间:2014-07-19 18:54:42

标签: sql

MS Access已生成以下查询:

SELECT Port.portName, Auth.portID, 
    Region.RegionName, Region.RegionID, 
    Auth.authID
FROM Region 
INNER JOIN (Auth INNER JOIN Port ON Auth.portID = Port.portID) 
    ON Region.RegionID = Port.RegionID;

我想要

GROUP BY Region.RegionID

当我将它添加到最后时,它告诉我PortName不是聚合函数的一部分。有人可以建议如何做到这一点吗?我已经尝试在SQL中的各个点插入它,但它似乎不起作用。

4 个答案:

答案 0 :(得分:0)

正在尝试这样做吗?:

SELECT Region.RegionID, Region.RegionName, Port.portName, Auth.authID
FROM Auth
INNER JOIN Port ON Port.portID = Auth.portID 
INNER JOIN Region ON Region.RegionID = Port.RegionID
ORDER BY Region.RegionID

答案 1 :(得分:0)

从您的评论中我认为您的意思是使用DISTINCT关键字而不是GROUP BY

SELECT DISTINCT Port.portName, 
Auth.portID, 
Region.RegionName, 
Region.RegionID, 
Auth.authID
FROM Region 
INNER JOIN Port ON Region.RegionID = Port.RegionID
INNER JOIN Auth ON Auth.portID = Port.portID);

答案 2 :(得分:0)

试试这个

SELECT Port.portName,Auth.portID,Region.RegionName,Region.RegionID,Auth.authID FROM Region INNER JOIN Auth on Region.RegionID = Auth.portID inner join Port on Port.portID = Auth.portID group by Port.portName,Auth.portID,Region.RegionName,Region.RegionID,Auth.authID;

答案 3 :(得分:0)

这将选择每个区域ID最大的端口

SELECT 
    Port.portName, 
    Auth.portID, 
    Region.RegionName, 
    Region.RegionID, 
    Auth.authID
FROM Region 
INNER JOIN Port ON Region.RegionID = Port.RegionID
INNER JOIN Auth ON Auth.portID = Port.portID
INNER JOIN (
    SELECT max(Port.portID) max_portID, Port.RegionID
    FROM Port
    GROUP BY Port.RegionID
) t1 ON t1.RegionID = Port.RegionID AND t1.max_portID = Port.portID

上述查询假设每Auth只有PortAuth,但如果每个Port可以有多个Auth,则您需要同样选择最大SELECT Port.portName, Auth.portID, Region.RegionName, Region.RegionID, Auth.authID FROM Region INNER JOIN Port ON Region.RegionID = Port.RegionID INNER JOIN Auth ON Auth.portID = Port.portID INNER JOIN ( SELECT max(Port.portID) max_portID, Port.RegionID FROM Port GROUP BY Port.RegionID ) t1 ON t1.RegionID = Port.RegionID AND t1.max_portID = Port.portID INNER JOIN ( SELECT max(Auth.authID) max_authID, Auth.portID FROM Auth GROUP BY Auth.portID ) t2 ON t2.portID = Port.portID AND t2.max_authID = Auth.authID {1}}以避免结果中存在重复的区域。

{{1}}