首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >H2DB中带-子句的子查询

H2DB中带-子句的子查询
EN

Stack Overflow用户
提问于 2013-01-18 02:09:21
回答 1查看 3.4K关注 0票数 0

我有一个简单的SQL查询来计数部门(子部门)中的所有员工,如下所示:

代码语言:javascript
复制
With Temp(id) AS
(
        Select d.id From DEPARTMENT d 
    Where d.id = 1 
    UNION ALL
    Select d.id From DEPARTMENT d JOIN Temp te ON d.idDepartment = te.id
)
Select count(*) From 
(
    Select e.id From Employee e Join Temp te On e.idDepartment = te.id
)

但是我错了"StackOverflow",我不知道哪里是错误,你能帮我吗?测试用例有一些数据:表部门:

代码语言:javascript
复制
ID----------departmentName-----------idDepartment(id parent)
1              A                         0
2              B                         1

表雇员:

代码语言:javascript
复制
id----------employeeName------------idDepartment
1              E_1                       1
2              E_2                       1
3              E_3                       2

所以当我选择一个部门的数量(A)->结果: 3,如果部门B->结果:1谢谢!

EN

回答 1

Stack Overflow用户

发布于 2013-01-19 09:28:48

我想我有一个可行的解决方案:

代码语言:javascript
复制
create table Department(id int, name varchar(255), idDepartment int);
create table Employee(id int, name varchar(255), idDepartment int);
insert into Department values(1, 'A', 0), (2, 'B', 1);
insert into Employee values(1, 'E1', 1), (2, 'E2', 1), (3, 'E3', 2);
with recursive temp(id) as (
    select 1 union all
    select d.id from temp te 
    inner join Department d on d.idDepartment = te.id
)
select count(*) from temp te 
inner join Employee e on e.idDepartment = te.id;
drop table Department;
drop table Employee;
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14391406

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档