我有一个动态数据透视查询,在条件语句中使用csv值。我创建了一个函数(splitstring(“ABC,sd”,“,”)),它拆分csv字符串并以表格形式返回,函数正在'IN'条款条件下工作,除了在'PIVOT'声明中......
insert into @filteredUsers select * from @users users
Where (
(@IncludeInactiveUsers = 1 AND ( users.Status = 'Active' OR (users.Status = 'Inactive')) )
OR (@IncludeInactiveUsers = 0 AND users.Status = 'Active')
)
SELECT @columns = STUFF((
SELECT DISTINCT ',' + QUOTENAME(NAME)
FROM @filteredUsers
FOR XML PATH('')
,TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '');
SELECT @SelectedColumns = STUFF((
SELECT DISTINCT ',ISNULL(' + QUOTENAME(NAME) + ', ''N'') AS [' + NAME + ']'
FROM @filteredUsers
FOR XML PATH('')
,TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '');
DECLARE @loanProgramChannels TABLE (
id UNIQUEIDENTIFIER
,NAME VARCHAR(500)
,[Broker] VARCHAR(2)
,[Correspond] VARCHAR(2)
,[Retail] VARCHAR(2)
);
insert into @loanProgramChannels select
id,
[Loan Program Name],
ISNULL([Broker],'N') as [Broker],
ISNULL([Correspond],'N') as [Correspond],
ISNULL([Retail],'N') as [Retail]
FROM
(
SELECT LoanPrograms.Id
, LoanPrograms.NAME AS [Loan Program Name]
, ' Y ' AS Y
, Channels.NAME AS [ChannelType]
FROM LoanPrograms
LEFT JOIN LoanProgramChannels ON LoanPrograms.id = LoanProgramChannels.Loanprogram_Id
LEFT JOIN Channels ON Channels.id = LoanProgramChannels.Channel_id
) programs
PIVOT
(
MAX(Y) FOR [ChannelType] IN ([Broker],[Correspond],[Retail])
)PivotTable
SELECT Name,Broker,Correspond,Retail, @SelectedColumns
FROM
(
SELECT LoanPrograms.NAME
,LP.[Broker]
,LP.[Correspond]
,LP.[Retail]
,(
CASE
WHEN UserParameterValues.value IS NULL
THEN ' N '
ELSE ' Y '
END
) AS value
,(users.FirstName + space(1) + users.LastName) FullName
FROM LoanPrograms
LEFT JOIN UserParameterValues ON LoanPrograms.id = UserParameterValues.ValueId
LEFT JOIN Parameters on UserParameterValues.ParameterId = Parameters.id
AND Parameters.Name = 'UwHierarchy'
LEFT JOIN users ON UserParameterValues.UserId = Users.Id
LEFT JOIN @loanProgramChannels LP ON LP.id = loanPrograms.id
) AS UsersTable
PIVOT
(
SUM(value)
FOR FullName IN( SELECT *
FROM dbo.SplitString(@UserNames, ',' ) ) AS pvt
不确定如何在我的PIVOT语句IN子句中使用相同的函数。?
答案 0 :(得分:1)
IN
子句中的Pivot
子句与IN
子句中的Where
运算符不同。
它指定了pivot的列,SQL Server需要一个常量的列列表,而不是表
为了使此数据透视查询正常工作,您必须使用动态sql。
我打算尝试重新编写你的代码,但是我不太确定你需要在数据透视表中使用哪些列,所以我只是给你这个解释动态数据透视技术的link在sql server中。