长时间的收听者,首次呼叫者。
我正在尝试通过经典的组织结构图学习Snowflake SQL中的递归。我正在尝试的输出将是每个员工经理(包括该经理的直接和间接员工)的总薪水。
create table Employee(
employeeid int primary key,
managerid int,
title string
);
INSERT INTO EMPLOYEE VALUES(1,NULL,'CEO');
INSERT INTO EMPLOYEE VALUES(2,1,'SVP 1');
INSERT INTO EMPLOYEE VALUES(3,1,'SVP 2');
INSERT INTO EMPLOYEE VALUES(4,2,'DIR 1');
INSERT INTO EMPLOYEE VALUES(5,2,'DIR 2');
INSERT INTO EMPLOYEE VALUES(6,2,'DIR 3');
INSERT INTO EMPLOYEE VALUES(7,3,'MGR 1');
INSERT INTO EMPLOYEE VALUES(8,3,'MGR 2');
INSERT INTO EMPLOYEE VALUES(9,3,'MGR 3');
INSERT INTO EMPLOYEE VALUES(10,9,'ASST');
create TABLE EMPLOYEE_SALARY(
EMPLOYEE_ID INT PRIMARY KEY,
SALARY INT
);
INSERT INTO EMPLOYEE_SALARY VALUES(1,100);
INSERT INTO EMPLOYEE_SALARY VALUES(2,90);
INSERT INTO EMPLOYEE_SALARY VALUES(3,90);
INSERT INTO EMPLOYEE_SALARY VALUES(4,80);
INSERT INTO EMPLOYEE_SALARY VALUES(5,80);
INSERT INTO EMPLOYEE_SALARY VALUES(6,80);
INSERT INTO EMPLOYEE_SALARY VALUES(7,70);
INSERT INTO EMPLOYEE_SALARY VALUES(8,70);
INSERT INTO EMPLOYEE_SALARY VALUES(9,90);
INSERT INTO EMPLOYEE_SALARY VALUES(10,60);
select
managerid,
sum(salary) as salary
from
(
select emp.managerid,
emp.employeeid,
sal.salary
from employee emp
inner join employee_salary sal on emp.employeeid = sal.employee_id
)
group by 1
start with managerid is Null
connect by managerid = prior employeeid
我收到的错误是“ SQL编译错误:错误行3在位置12的无效标识符'SALARY'”。
预先感谢您提供的任何指导。
答案 0 :(得分:1)
我将使用递归公用表表达式来解决这个问题。 Snowflake支持该标准语法,我发现遵循connect by
子句更容易:
with cte as (
select managerid, employeeid from employee
union all
select c.managerid, e.employeeid
from cte c
inner join employee e on e.managerid = c.employeeid
)
select c.managerid, sum(s.salary) total_salaries
from cte c
inner join employee_salary s on s.employeeid = c.employeeid
group by c.managerid