SQL Server:加入两个数据透视表

时间:2014-09-03 13:50:41

标签: sql join pivot

我试图与自己创建一个表连接。因此,例如,在表格下方基于D(借方)和C(贷方)的总和,但我需要将表格与其自身连接以添加显示" D"的计数的其他列。进入" C"再加上两个额外的列,显示总和和总计数。如何加入下表以创建其他列?

输入表

GL_BU   GL_Source   GL_JE_Type          GL_Amount   Amount_Prefix
------------------------------------------------------------------
202     Payables    Purchase Invoices        1234               C
202     Payables    Purchase Invoices         123               D
202     Inventory   Inventory                 123               C
202     Payables    Purchase Invoices        1234               C

输出表

GL_BU GL_Source   GL_JE_Type    Amount D Amount C Count D Count C Total Count Total Amount
------------------------------------------------------------------------------------------
202   Spreadsheet XXXXX         1234     123            1        1          2      1357
202   Manual      XXXXX         1234     123            2        2          4      1357
202   Manual      XXXXX         1234     123            1        1          2      1357
202   Inventory   XXXXX         1234     123            4        4          8      1357
202   Sales Order XXXXXX        1234     123            1        1          2      1357

当前代码

SELECT *
    FROM 
            (SELECT 
                    [GL_Business_Unit]
                    ,[GL_Source]
                    ,[GL_JE_Type]
                    ,([GL_Amount])
                    ,[Amount_Prefix]
              FROM [03_rdm].[table_2013]) as t
                Pivot(SUM([GL_Amount])
                FOR [Amount_Prefix] IN (D,C)) AS pvt1 

SQLFiddle http://sqlfiddle.com/#!3/92369/2

中的当前代码链接

1 个答案:

答案 0 :(得分:2)

您的样本数据与您想要的结果不符,因此我猜测这就是您所需要的。您可以使用PIVOT来获取结果,但似乎通过CASE表达式使用聚合函数和一些条件逻辑更容易实现这一点:

select 
  GL_BU,
  GL_Source,
  GL_JE_Type,
  sum(case when Amount_Prefix = 'D' then GL_Amount else 0 end) Amount_D,
  sum(case when Amount_Prefix = 'C' then GL_Amount else 0 end) Amount_C,
  sum(case when Amount_Prefix = 'D' then 1 else 0 end) Count_D,
  sum(case when Amount_Prefix = 'C' then 1 else 0 end) Count_C,
  count(*) TotalCount,
  sum(GL_Amount) TotalAmount
from table_2013
group by GL_BU, GL_Source, GL_JE_Type;

请参阅SQL Fiddle with Demo