2012-09-24 104 views
2

我需要找到最少與其關聯的客戶端數量的人員的ID,以便將當前新客戶端分配給該員工。COUNT選擇和本地變量存儲

我已經使用以下來建立這個工作人員的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 

我該如何抓住第一選擇中的judgeId?通常我會做類似的事情;

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事務中執行後續更新語句。

所以......任何幫助,甚至任何人可以提供補救措施,將不勝感激。

在此先感謝!

+0

我沒有一個MSSQL服務器方便的進行測試,但不能你只要把聚合函數' COUNT(JA.judgeId)'在你的'ORDER BY'子句中(而不是將它包含在你的'SELECT'中)? – Crontab

+0

我現在就試試,但這聽起來很可能。 –

+0

@Crontab號碼不起作用。它只是返回-1代碼並且沒有結果/記錄 –

回答

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 
+0

不幸的是,這抱怨一個無效的列名'COUNT'有什麼建議嗎?謝謝。 –

+1

@PhillHealey - 應該是'ORDER BY COUNT(JA.judgeId)' –

+0

@Martin Smith - 這麼想。只是想確定。感謝您的確認。 ;-) –

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 
+0

對不起,我感到困惑。錯誤地,在編輯時我刪除了頂部(1)。 – Pradeeshnarayan

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) 
+0

它看起來像會起作用,但我會從上面的@Dems得到答案,因爲它給了我輸出結果的可能性。感謝您的迴應。真的很感激。謝謝。 –