您可以使用遞歸CTE來構建組的層次結構。之後,您可以將您的用戶和交易加入到此層次結構中。
下面是一個使用你的表定義的例子:
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]
上面的查詢會給你這樣的輸出格式:
PARENT_NAME GROUP_NAME HierarchyLevel USER_NAME TransactionSum TransactionAvg
-------------- -------------- -------------- ------------ -------------- --------------
NULL Company 0 NULL NULL NULL
Company Michigan 1 User 3 44 22
Company Michigan 1 User 4 100 100
Company New York 1 User 1 310 103
Company New York 1 User 2 570 190
Company San Diego 1 User 5 54 54
Company San Diego 1 User 6 NULL NULL
Michigan Accounts 2 User 9 NULL NULL
Michigan Finance 2 User 10 NULL NULL
New York Administration 2 User 7 NULL NULL
New York Support 2 User 8 NULL NULL
San Diego Sales 2 NULL NULL NULL
San Diego Service 2 NULL NULL NULL
您沒有表現出什麼努力,但我建議您在表示層中處理這種類型的輸出格式。 –
請求的格式不能從您的描述中清楚。請以表格格式顯示所需的輸出。 – dybzon
好奇你的_schema_有數據,但沒有數據類型。並且有'Group_Id'和'User_Id',但沒有'Transaction_Id'。請閱讀[this](http://spaghettidba.com/2015/04/24/how-to-post-a-t-sql-question-on-a-public-forum/)瞭解一些關於改善問題的提示。 – HABO