可以在没有聚合功能的情况下编写此查询吗?

时间:2019-04-17 19:09:58

标签: sql sql-server tsql

SELECT l.LocID, COUNT(ulr.UserID)
FROM Locations l
LEFT OUTER JOIN UserLocationRights ulr ON l.LocID = ulr.LocID
LEFT OUTER JOIN Devices d ON l.LocID = d.LocID
LEFT OUTER JOIN UserModelRights umr ON d.ModelName = umr.ModelName
    AND ulr.UserID = umr.UserID
GROUP BY l.LocID, ulr.UserID, d.ModelName
ORDER BY l.LocID, ulr.UserID

我希望结果为LocID中所有条目的 all Locations,第二列为对该位置拥有以下权限的用户数:也有权对{{1}中的Devices中的Location中的UserModelRights中的至少一个进行

我只能弄清楚如何得到我想要的东西:

SELECT l.LocID, IsNull(UserHasModelRightInLoc.UserCount, 0) UserCount
FROM Locations l
LEFT OUTER JOIN (
    SELECT ulr.LocID, COUNT(UserModelRightsPerLocation.UserID) UserCount
    FROM UserLocRights ulr
    INNER JOIN (
        SELECT l.LocID, umr.UserID
        FROM UserModelRights umr
        INNER JOIN Devices d ON umr.ModelName = d.ModelName
        INNER JOIN Locations l ON d.LocID = l.LocID
        GROUP BY umr.ModelName, umr.UserID, l.LocID
        ) UserModelRightsPerLocation ON ulr.LocID = UserModelRightsPerLocation.LocID
        AND ulr.UserID = UserModelRightsPerLocation.UserID
    GROUP BY ulr.LocID
    ) UserHasModelRightInLoc ON l.LocID = UserHasModelRightInLoc.LocID
ORDER BY l.LocID

我不知道这是否可行,但是我假设可以使用第一个小得多的查询来使用GROUP BY来获取想要的内容。问题是我认为我需要按特定顺序执行多个GROUP BY,但我不知道这在SQL中是否可行或有意义。

是否有一种无需使用聚合函数即可获得所需结果的方法?如果没有,也许将其缩小到单个?

1 个答案:

答案 0 :(得分:1)

如果没有示例数据,我很难做到这一点。但是根据您的描述,这可能会满足您的要求:

SELECT l.LocID, COUNT(DISTINCT ulr.UserID)
FROM Locations l LEFT JOIN
     UserLocationRights ulr
     ON l.LocID = ulr.LocID LEFT JOIN
     Devices d
     ON l.LocID = d.LocID LEFT JOIN
     UserModelRights umr
     ON d.ModelName = umr.ModelName AND
        ulr.UserID = umr.UserID
GROUP BY l.LocID
ORDER BY l.LocID;