Query the SQL statements of all upper-level departments

Source: Internet
Author: User

Create Table testdept (
deptid int identity (1,1) primary key,
deptname varchar (16),
superdept int
);
insert into testdept (deptname, superdept) values ('general manager ', 0);
insert into testdept (deptname, superdept) values ('finance Department ', 1);
insert into testdept (deptname, superdept) values ('engineering Department', 1);
insert into testdept (deptname, superdept) values ('accounting Department ', 2);
insert into testdept (deptname, superdept) values ('cashier Department', 2);
insert into testdept (deptname, superdept) values ('Beijing Engineering Office ', 3);
insert into testdept (deptname, superdept) values ('nanjing Engineering Office', 3);


You want to query the result as follows:
Deptid deptname superdept
0. General Manager
1. General Manager of Engineering Department
2. General Manager of Finance Department
3. Finance Department of Accounting Department
4. Cashier Finance Department
5 Beijing Engineering Office Engineering Department
6 Nanjing Engineering Office Engineering Department
 

 

========================================================== ====

 

SelectA. deptid, A. deptname, isuperdept=Isnull(B. deptname, A. deptname)

FromTestdept

LeftJoinTestdept B

OnA. superdept=B. deptid

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.