0

这几天我一直在纠结这个。我有经理表、分配给他们的站点以及分配给这些站点的种植者。我需要知道经理有多少种植者。经理被分配到站点而不是种植者,所以我必须通过这个练习来找出特定经理有多少种植者,具体取决于分配给他拥有的每个单独站点的种植者。一个站点只有一个种植者。我可以很容易地获得特定经理的种植者数量,但我想返回一个包含每个经理的种植者数量的表格,我很难过。

我有以下代码:

DECLARE @ManagerID     INT
DECLARE @getManagerID  CURSOR 
SET @getManagerID =  CURSOR FOR
SELECT ID
FROM   Managers

     OPEN @getManagerID
     FETCH NEXT
     FROM @getManagerID INTO @ManagerID
WHILE @@FETCH_STATUS = 0
BEGIN
    SELECT COUNT(Grower) AS NumGrowers
    FROM   Growers
    WHERE  Growers.ID IN 
    (
       SELECT sitesg.Grower
       FROM   SitesG
       WHERE  SitesG.id IN 
       (
          SELECT SITE
          FROM   ManagerSites
          WHERE  ManagerSites.Manager IN 
          (
             SELECT ID
             FROM Managers
             WHERE ID = @ManagerID
          )
       )
    )

    FETCH NEXT
    FROM @getManagerID INTO @ManagerID
END
     CLOSE @getManagerID
     DEALLOCATE @getManagerID

这给了我一堆结果,我可能可以将它们存储在临时表中,但必须有更好的方法。有任何想法吗?

-乔

4

1 回答 1

1

是的,请放弃游标和所有嵌套的子查询。这正是连接的用途......

SELECT ManagerID = m.ID, NumGrowers = COUNT(DISTINCT g.ID)
  FROM dbo.Managers AS m
  INNER JOIN dbo.ManagerSites AS s
  ON s.Manager = m.ID
  INNER JOIN dbo.SitesG AS sg
  ON s.SITE = sg.id
  INNER JOIN dbo.Growers AS g
  ON sg.Grower = g.ID
  GROUP BY m.ID;

事实上,如果你只关心ManagerID你可以简化这个:

SELECT ManagerID = s.Manager, NumGrowers = COUNT(DISTINCT g.ID)
  FROM dbo.ManagerSites AS s
  INNER JOIN dbo.SitesG AS sg
  ON s.SITE = sg.id
  INNER JOIN dbo.Growers AS g
  ON sg.Grower = g.ID
  GROUP BY s.Manager;

s.Manager = m.ID顺便说一句,加入和之类的东西非常令人困惑sg.Grower = g.ID。为什么不在模型中出现的任何地方都将事物ManagerIDGrowerID称为相同的事物?这肯定会使这些连接更加直观。

于 2013-01-22T04:49:18.093 回答