平均值/总和从层次结构的底部到顶部 - SQL Server

时间:2017-08-05 09:07:25

标签: sql-server tsql hierarchy

我们在SQL Server中有3个表

Here is the Schema of the tables

组将具有层次结构,并且这些层将映射到用户表中的用户。每个用户都有交易表中的交易。

我们希望输出为:

- Company (810)     
    - New York (810)            
        - Administration (310)
            - USER 1    100 
            - USER 2    200 
            - USER 3     10 
        - Support (500)
            - USER 4    500

    - Michigan          
        - Accounts      
    - San Diego         

有人可以建议使用SQL查询来实现这个目标吗?

2 个答案:

答案 0 :(得分:0)

您可以使用递归CTE来构建组的层次结构。之后,您可以将用户和交易加入此层次结构。

以下是使用表定义的示例:

(((0)) * 1)

上面的查询将为您提供如下输出格式:

WITH GroupHierarchy AS (
    SELECT
        GROUP_ID,
        GROUP_NAME,
        PARENT_ID,
        CONVERT(NVARCHAR(200),NULL) AS PARENT_NAME,
        0 AS HierarchyLevel
    FROM GROUPS g
    WHERE g.PARENT_ID IS NULL
    UNION ALL
    SELECT 
        g.GROUP_ID,
        g.GROUP_NAME,
        g.PARENT_ID,
        gh.GROUP_NAME AS PARENT_NAME,
        HierarchyLevel + 1 AS HierarchyLevel
    FROM GROUPS g
        INNER JOIN GroupHierarchy gh ON gh.GROUP_ID = g.PARENT_ID
)
SELECT 
    gh.PARENT_NAME,
    gh.GROUP_NAME,
    HierarchyLevel,
    [USER_NAME],
    SUM([VALUE]) AS TransactionSum,
    AVG([VALUE]) AS TransactionAvg
FROM GroupHierarchy gh
    LEFT OUTER JOIN USERS u ON u.GROUP_ID = gh.GROUP_ID
    LEFT OUTER JOIN TRANSACTIONS t on t.[USER_ID] = u.[USER_ID]
GROUP BY PARENT_NAME, GROUP_NAME, HierarchyLevel, [USER_NAME]
ORDER BY PARENT_NAME, GROUP_NAME, HierarchyLevel, [USER_NAME]

答案 1 :(得分:0)

This is all built in to SQL now. Go with:

GROUP BY ROLLUP(PARENT_NAME, GROUP_NAME, [USER_NAME])

The lower level fields will be NULL when the values are being rolled-up.

See https://technet.microsoft.com/en-us/library/ms189305(v=sql.90).aspx for more, and for how to deal with NULLs in the source fields (if applicable), and beutify the NULLs in the output. (Lots of ISNULLs.)