0

我有这个选择语句

declare @t table (Percentage float)
DECLARE @acc INT 
SET @acc = 1
DECLARE @max INT 
select @max = max(HireID) from NewHire
WHILE (@acc <= @max)
    BEGIN
        IF (@acc in (select HireID from NewHire))
            BEGIN try
                insert into @t  
                select
                    CAST((select COUNT(*) from Hire_Response WHERE HireID = @acc AND (HireResponse = 0 OR HireResponse = 1)) as FLOAT) / 
                    CAST((select COUNT(*) from Hire_Response WHERE HireID = @acc) as FLOAT)
            END try
            begin catch
                insert into @t 
                select 0.0
            end catch
        set @acc = @acc + 1
    END
select * from @t

在这段代码中,我按 ID 循环遍历所有 NewHire 记录,从 1 到最高记录。我意识到这不再是我想做的事情了。现在基本上我有这个名为的存储过程sp_selectNewHire2SQL,它以特定方式获取 NewHire 表。我想调用它,并获取它的返回记录集,然后从上到下循环遍历它。

注意:从 id 1 到最高的循环将不再起作用,因为 id 的顺序可能会混淆。

有没有办法做到这一点?

谢谢。

4

1 回答 1

3

作为一个单一的选择,像这样

select
    NH.HireID,
    ISNULL(1E0 *
          COUNT(CASE WHEN HireResponse IN (0,1) THEN HR.HireID END) / 
          NULLIF(COUNT(HR.HireID), 0)
       , 0) AS percentage
from
    NewHire NH
    LEFT JOIN
    Hire_Response HR ON NH.HireID = HR.HireID
group by
    NH.HireID
于 2013-05-14T14:58:21.730 回答