2015-11-20 90 views
0

我有这样的一个表:汇总表生成的SQL Server

enter image description here

我想看看在这样的摘要视图数据:

enter image description here

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

对不起我的小英文。

+1

你能分享到目前为止,你做了什么? – wogsland

+1

这种事情在前端是最好的,特别是如果你需要在这样的特定行中有空值。它当然可以在SQL中完成,它只是一个错误的地方。如果您可以在sqlfiddle上发布一些数据,我们可以提供帮助。 –

+0

你想看看做一个'Pivot' –

回答

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 
+0

其他意见,建议枢纽或前端开发。这些对于某些情况来说都是很好的解决方案,但是我遇到过这样的环境:数据使用者要么以可怕的方式正确显示数据(例如BIRT及其基于Rhino/Javascript/Java的混合脚本引擎)或者完全无法访问(例如,基于从数据库接收到的确切设置,仅出现在Excel电子表格中的“哑”报告功能)。换句话说,这个特定的请求是有效的,可能需要直接的解决方案而不是解决方法。 – Paurian

+0

谢谢@Paurian。这个解决方案对我来说非常方便。 – phoenix