我有一个动态数据透视查询,可以将行转换为列。目前,我将所有数据都放在一个表中,但如果两个单独的表更容易,则可以将它分开。
我只需要一些这样的ChargeNames列(包含相关费用)是否可以只旋转表的一部分并将新的Pivot表连接到源表上?
或者我可以创建一个包含所需数据的新表并将其转移,并将其连接到另一个表吗?
道歉,如果听起来有些混乱
包含所有数据的源表
数据透视表(数据透视表的列是费用名称)
代码 - 声明和填充表格
--Create temporary table
CREATE TABLE ##tempGetPaymentAnalysisByMember
(
MemberID NVARCHAR(MAX),
FirstName NVARCHAR(MAX),
Surname NVARCHAR(MAX),
CategoryName NVARCHAR(MAX),
InvoiceID INT,
ChargeNames NVARCHAR(MAX),
ChargeAmount INT,
TotalAmount INT
)
--Populate the table
INSERT INTO ##tempGetPaymentAnalysisByMember(MemberID, FirstName, Surname, CategoryName, InvoiceID, ChargeNames, ChargeAmount, TotalAmount)
SELECT Member.ID, Member.FirstName, Member.Surname, Category.Name, Invoice.ID, ChargeType.Name, Charge.Amount, Invoice.Amount
FROM dbo.Member, dbo.Category, dbo.Invoice, dbo.ChargeType, dbo.Charge
WHERE Category.ID = Member.CategoryID
AND Member.ID = Invoice.MemberID
AND Charge.ChargeTypeID = ChargeType.ID
AND Charge.InvoiceID = Invoice.ID
--Test select to check if data is correct
SELECT * FROM ##tempGetPaymentAnalysisByMember
数据透视查询
SELECT @ColumnName = ISNULL(@ColumnName + ',','')
+QUOTENAME(ChargeNames)
FROM (SELECT DISTINCT ChargeNames FROM ##tempGetPaymentAnalysisByMember) AS ChargeName
SET @DynamicPivotQuery =
'SELECT ' + @ColumnName +
' FROM ##tempGetPaymentAnalysisByMember
PIVOT(MIN(ChargeAmount)
FOR ChargeNames IN (' + @ColumnName + ')) AS PivotTable'
EXEC sp_executesql @DynamicPivotQuery
非常感谢
答案 0 :(得分:0)
我设法让它工作而不需要额外的桌子。
我能够将两张桌子连在一起,只在选定数量的柱子上执行PIVOT,而我之前并不知道你可以这样做。
我理解下面的代码需要稍微清理一下以阻止可能的SQL注入攻击,但是我会离开它直到我让整个程序工作。
SELECT @ColumnName = ISNULL(@ColumnName + ',','')
+QUOTENAME(ChargeName)
FROM (SELECT DISTINCT ChargeName FROM ##chargesTable) AS ChargeName
SET @DynamicPivotQuery =
'SELECT MemberID, FirstName, Surname, CategoryName, TotalAmount, ' + @ColumnName +
' FROM ##chargesTable
PIVOT(MIN(ChargeAmount)
FOR ChargeName IN (' + @ColumnName + ')) AS PivotTable
ORDER BY MemberID'
EXEC sp_executesql @DynamicPivotQuery