[英]Declare a Table Variable based on dynamic pivot columns statement
I want to declare a table variable and fill it from the pivot with dynamic column to perform join statement.我想声明一个表变量并使用动态列从 pivot 填充它以执行连接语句。
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
SELECT @cols =
STUFF((SELECT DISTINCT ',' + QUOTENAME(ColName)
FROM [sbs].[ProposalAmounts]
GROUP BY ColName, ProposalID
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
SET @query = N'SELECT ProposalID, ' + @cols + N' from
(select ProposalID, Amount, ColName from [sbs].[ProposalAmounts]) x
PIVOT
(MAX(Amount)for ColName in (' + @cols + N')) p '
EXEC sp_executesql @query;
This is what I've done so far and I'm confused as to how to declare a table variable that has dynamic columns in it.这是我到目前为止所做的,我对如何声明一个包含动态列的表变量感到困惑。
This is the result of the query above:这是上面查询的结果:
And this is the result of the table I want to perform join statement:这是我要执行连接语句的表的结果:
Like Jeroen Mostert commented, you need to make everything dynamic.就像 Jeroen Mostert 评论的那样,你需要让一切都充满活力。
I would suggest to put the join inside the dynamic query.我建议将连接放在动态查询中。 Instead of a table variable, I use a common table expression.
我使用公共表表达式而不是表变量。
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX);
SELECT @cols =
STUFF((SELECT DISTINCT N', ' + QUOTENAME([ColName])
FROM [_tmp_].[ProposalAmounts]
GROUP BY [ColName], [ProposalID]
FOR XML PATH(N''), TYPE).value(N'.', N'NVARCHAR(MAX)'), 1, 2, N'')
SET @query = N'
WITH [CTE_Pivoted_ProposalAmounts] AS
(
SELECT [ProposalID], ' + @cols + N'
FROM
(SELECT [ProposalID], [Amount], [ColName] FROM [sbs].[ProposalAmounts]) x
PIVOT (MAX([Amount]) FOR [ColName] IN (' + @cols + N')) p
)
SELECT *
FROM
[sbs].[OtherTable] ot
INNER JOIN [CTE_Pivoted_ProposalAmounts] ppa ON ppa.[ProposalID] = ot.[ProposalID];
';
EXEC sp_executesql @query;
You need to replace [sbs].[OtherTable]
with the actual name of the table you want to join with.您需要将
[sbs].[OtherTable]
替换为要加入的表的实际名称。 And you might also tweak the join criteria and the fields in the SELECT clause.您还可以调整 SELECT 子句中的连接标准和字段。 This code here is just a simple example.
这里的代码只是一个简单的例子。 I assume you will manage to fix the query yourself to make it behave as you expect.
我假设您将设法自己修复查询以使其按预期运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.