(T-SQL):如何使用结果集A计算结果集B?

时间:2015-07-11 04:05:16

标签: sql sql-server tsql join resultset

我有2个查询,A和B,我目前彼此独立使用。它们都返回员工ID和一些度量值。我现在想要使用从查询B中的结果集A返回的员工ID。

A的查询结构如下:

select employee_id from employee where employee_team = 1 and employee_role = 1

B的查询结构如下:

declare @tester int = 123450 --plug in employee ID
select employee_id
,employee_name
,sum(case 
  when notes.note_author!=employee_id and logs.log_date<@today 
  then 1 else 0 end) as metric
from notes
inner join note_to_log_bridge as br on notes.note_id=br.note_id
inner join logs on br.log_id=logs.log_id
inner join employee on employee_id=@Tester

如果我想获得5名员工的B指标,我必须运行查询B 5次,每次更改@Tester变量。我想找到一些自动化方法,以便为结果集A中的每个employee_id获取查询B的指标。

我尝试将存储结果集A作为CTE并使用while循环运行查询B:

declare @line=1
with cte (employee_id) as <query_a>
while (@line<=count(cte.employee_id))
begin <query b>...

我从未完成此查询,因为我发现while无法跟随CTE的创建。

我尝试使用表变量:

declare @set_a (employee_id int)
insert into @set_a <query a>

但是当我尝试在查询B中使用@set_a时,我收到一条消息,说我需要声明标量变量@set_a。

我尝试使用临时表并得到“无法绑定”错误。

我没有想法。我是否在任何类似正确方向的问题上处理这个问题?这甚至可能吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

是的,你可以使用光标,它可以很好地工作。

但是,如果您有超过5行,您可以考虑使用CROSS APPLY在一个查询中完成所有操作。它可能比光标更快。

select
    employee.employee_id
    ,CA.*
from
    employee
    CROSS APPLY
    (
        <put your query B here 
        and replace all references to parameter @Tester 
        with employee.employee_id>
    ) AS CA
where employee.employee_team = 1 and employee.employee_role = 1

你可以这样考虑这个运算符:对于主外部查询中的每一行,CROSS APPLY运行内部查询B,可以引用外部查询A中的行的值(在这种情况下{ {1}})。

答案 1 :(得分:0)

使用Cursor

  

如果我想获得5名员工的B指标,我必须运行查询B 5   次,每次更改@Tester变量。

DECLARE @empid int;
DECLARE vend_cursor CURSOR
    FOR select employee_id from employee where employee_team = 1 and employee_role = 1
OPEN vend_cursor
FETCH NEXT FROM vend_cursor into @empid;
WHILE @@FETCH_STATUS = 0    
BEGIN  
// your query with @mpid 
FETCH NEXT FROM db_cursor INTO @name   
END   
CLOSE vend_cursor
DEALLOCATE vend_cursor
相关问题