COUNT选择和本地变量存储

时间:2012-09-24 13:47:39

标签: sql sql-server sql-server-2008 tsql

我需要找到与其关联的客户端数量最少的人的ID,以便将当前的新客户端分配给该员工。

我已使用以下内容建立此工作人员的ID,如下所示;

    SELECT TOP(1) JA.judgeID, COUNT(JA.judgeId) AS COUNT
    FROM recJudgeAssignment AS JA
    LEFT JOIN recEntrantStatus AS ES
    ON JA.bandId = ES.entrantId
    GROUP BY JA.judgeId, ES.roundId
    HAVING ES.roundId = @round
    ORDER BY COUNT

但我需要将其作为一个局部变量来捕获,以便在下一个语句中使用;

    UPDATE recJudgeAssignment
    SET judgeId = @judge
    WHERE roundId = @round
    AND bandId = @entrantId

如何在第一个选择中抓住judId?通常我会做类似的事情;

    SELECT @judge =(SELECT TOP(1) JA.judgeID, COUNT(JA.judgeId) AS COUNT
    FROM recJudgeAssignment AS JA
    LEFT JOIN recEntrantStatus AS ES
    ON JA.bandId = ES.entrantId
    GROUP BY JA.judgeId, ES.roundId
    HAVING ES.roundId = @round
    ORDER BY COUNT)

这当然不起作用,因为select正在返回judgeId和COUNT。我宁愿不必将第一个选择的结果发送回网页,然后在单独的web> db transaction中执行后续更新语句。

所以...任何帮助甚至是任何人可以提供的补救措施,都将不胜感激。

提前致谢!

3 个答案:

答案 0 :(得分:3)

-- Query the DB for your variables
-- (I have also moved the HAVING clause to a WHERE clause.)
------------------------------------------------------------
SELECT TOP(1)
  @judgeID = JA.judgeID,
  @count   = COUNT(JA.judgeId)
FROM
  recJudgeAssignment AS JA
LEFT JOIN
  recEntrantStatus AS ES
    ON JA.bandId = ES.entrantId
WHERE
  ES.roundId = @round
GROUP BY
  JA.judgeId, ES.roundId
ORDER BY
  COUNT

-- Update the DB
------------------------------------------------------------
UPDATE
  recJudgeAssignment
SET
  judgeId = @judgeID
WHERE
      roundId = @round
  AND bandId  = @entrantId

-- Return the variables to the client
------------------------------------------------------------
SELECT
  @judgeID     AS judgeID,
  @count       AS count

答案 1 :(得分:2)

SELECT top(1) @judge = JA.judgeID, @count_j =COUNT(JA.judgeId)
    FROM recJudgeAssignment AS JA
    LEFT JOIN recEntrantStatus AS ES
    ON JA.bandId = ES.entrantId
    GROUP BY JA.judgeId, ES.roundId
    HAVING ES.roundId = @round
    ORDER BY COUNT

答案 2 :(得分:1)

只看第一个查询
请试试这个

SELECT TOP(1) JA.judgeID
FROM recJudgeAssignment AS JA
LEFT JOIN recEntrantStatus AS ES
 ON   JA.bandId = ES.entrantId 
 AND  ES.roundId = @round   
GROUP BY JA.judgeId, ES.roundId
ORDER BY COUNT(JA.judgeId)