SQL Server uses recursive query data

Source: Internet
Author: User

Function Description: There are two tables, a Business Unit table A (all the business unit information of a company in Table a), and the other table for user table B (in table B, where all users of a company are in the business Unit information), requiring the use of SQL statements to query the number of users in each department (note: When counting the number of users Need to count the users of all sub-departments below);

Table A:

Table B:

Method Description:

Use a recursive approach to SQL Server:

1, the first joint two tables query data, and the results of the query is stored in the temporary table;

2, using the CTE method to query data from the temporary table;

The specific SQL script is as follows:

    

SelectB. User name, b. Business unit, A. Parent DepartmentInto#Table1From BLeft join A on B. Business unit name = A. primary key;  With CTE  as ( select user name, business unit,
Parent department, from #Table1 c where c. business unit = 102
UNION ALL
Select
User name,
Business Unit,
Parent Department
From CTE D INNER join #Table1 E on D. Business unit = E. Parent department)
Select SUM (user name) number of users
From CTE

drop table #Table1

SQL Server uses recursive query data

Related Article

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.