SQL Server中的摘要表生成

时间:2015-11-20 15:52:30

标签: sql sql-server tsql

我有一张这样的表:

enter image description here

我希望在摘要视图中看到这样的数据:

enter image description here

我需要T-SQL脚本的帮助。谢谢。

抱歉我的小英语。

1 个答案:

答案 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