简体   繁体   English

父/子数据库如何“汇总”?

[英]How to do a parent/child database 'roll-up'?

How do you properly go about rolling up and selecting all users for each parent company until there are no more parent companies? 您如何正确地汇总并选择每个母公司的所有用户,直到没有更多母公司?

I am using SQL Server 2008 R2 and I need to check if there is a @ParentID then select all the users for that company, if there is a @ParentID on that company do the same thing, ad infinity? 我正在使用SQL Server 2008 R2,我需要检查是否有@ParentID,然后选择该公司的所有用户,如果该公司上有@ParentID,则做同样的事情,广告无穷大?

Thanks. 谢谢。 I am completely new to Rollups but am just trying something like the below to get the basic query idea started. 我对汇总完全陌生,但只是尝试使用以下类似方法来开始基本的查询思路。

USE [DB]

DECLARE @UserName VARCHAR(250) = 'crusher@abc.com'
DECLARE @ParentID INT = -1

WHILE (@ParentID <> 0)
BEGIN
    SELECT @ParentID = CASE 
            WHEN ParentCompanyID IS NULL
                THEN 0
            ELSE ParentCompanyID
            END
    FROM User2Company a
    LEFT JOIN dbo.CompanyInfo b ON a.CompanyID = b.CompanyID
    LEFT JOIN dbo.widgets ON a.companyid = widgets.companyid
    WHERE a.UserName = @UserName

    PRINT @ParentID
END

    --SELECT * FROM CompanyInfo
    --WHERE CompanyID = 100274
    --SELECT *
    --FROM CompanyInfo
    --WHERE CompanyID = 100273

The commented code is just a hypothetical example of where the original query found a parent CompanyID of 100274... then THAT company found a parent CompanyID of 100273... until ultimately CompanyID 100273 had a ParentCompanyID of 0 in it's column. 注释的代码只是一个假设示例,该示例在原始查询中找到父公司ID为100274 ...然后该公司找到父公司ID为100273 ...直到最终公司ID 100273在其列中的父公司ID为0。

HOw is this typically done? 通常如何完成?

DESIRED Output from the first query might look like this: 第一个查询的期望输出可能如下所示:

100274
100273
0

At which point I would fetch all user's from those company id's. 此时,我将从这些公司ID中获取所有用户。

It's typically done with a recursive CTE: 通常通过递归CTE完成:

;WITH
    tmp AS
    (
        SELECT  CompanyID,
                ParentCompanyID
        FROM    CompanyInfo
        WHERE   CompanyID = 100274
        UNION ALL
        SELECT      com.CompanyID,
                    com.ParentCompanyID
        FROM        CompanyInfo com
        INNER JOIN  tmp         tmp ON com.CompanyID = tmp.ParentCompanyID -- This is the recursive part
    )

SELECT * FROM tmp

And as others have said, avoid using loops in SQL Server. 正如其他人所说,请避免在SQL Server中使用循环。 If you have to use loop, 99% of the time you are not using SQL Server properly. 如果必须使用循环,则有99%的时间没有正确使用SQL Server。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM