答案 0 :(得分:2)
这有效:
[配置]
CREATE TABLE #PaymentTable ( Id INT IDENTITY, AccountGroupId INT, AccountId INT, Payment INT )
INSERT INTO #PaymentTable ( AccountGroupId, AccountId, Payment )
SELECT 1, 1, 5 UNION ALL SELECT 1, 1, 5 UNION ALL
SELECT 1, 2, 5 UNION ALL SELECT 2, 4, 5 UNION ALL
SELECT 2, 3, 5 UNION ALL SELECT 2, 3, 5 UNION ALL
SELECT 2, 4, 5
CREATE TABLE #Group ( AccountGroupId INT, GroupName VARCHAR(100) )
INSERT INTO #Group ( AccountGroupId, GroupName )
SELECT 1, 'Group 1' UNION Select 2, 'Group 2'
CREATE TABLE #Account ( AccountId INT, AccountName VARCHAR(100) )
INSERT INTO #Account ( AccountId, AccountName )
SELECT 1, 'John' UNION Select 2, 'Edvard' UNION
SELECT 3, 'David' UNION SELECT 4, 'Jimi'
[查询]
SELECT
[Group],
Account,
TotalPayment
FROM
(
SELECT
#Group.AccountGroupId AS GroupId,
GroupName AS [Group],
'' AS Account,
SUM( Payment ) AS TotalPayment,
0 AS InnerOrder
FROM
#PaymentTable,
#Group
WHERE
#Group.AccountGroupId = #PaymentTable.AccountGroupId
GROUP BY
#Group.AccountGroupId,
#Group.GroupName
UNION
SELECT
AccountGroupId AS GroupId,
'' AS [Group],
AccountName AS Account,
SUM( Payment ) AS TotalPayment,
1 AS InnerOrder
FROM
#PaymentTable,
#Account
WHERE
#Account.AccountId = #PaymentTable.AccountId
GROUP BY
AccountGroupId,
AccountName
) AS inner_query
ORDER BY
GroupId,
InnerOrder,
Account