如何将使用Delare语句的SQL Pivot查询联接到普通SQL查询

时间:2018-10-24 18:55:49

标签: sql-server

很抱歉,如果这不是问这个问题的最佳方式,但我被困在这一点上,我尝试进行研究但无济于事,尝试加入这两个查询:

SELECT [id]
  ,[title]
  ,[desc]
FROM [localTest].[dbo].[main];

DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
select @cols  = STUFF((SELECT distinct ',' + QUOTENAME([Year]) from [localTest].[dbo].[Years] FOR XML PATH(''),TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
    set @query = 'SELECT [ID], ' + @cols + ' from (select [ID], [Year], [Amount] FROM [localTest].[dbo].[Years] ) x pivot (min([Amount]) for [Year] in (' + @cols + ')) p '
execute(@query);

在这里寻找最终结果:

enter image description here

2 个答案:

答案 0 :(得分:1)

我知道了,这是我的解决方案:

DECLARE @cols AS NVARCHAR(MAX);
 SELECT @cols = STUFF((SELECT distinct ',' + QUOTENAME([Year]) FROM [localTest].[dbo].[Years] FOR XML PATH(''),TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'');
DECLARE @Sql VARCHAR(max);
 SELECT @Sql = 'SELECT * FROM [localTest].[dbo].[main] a join (
            SELECT * FROM (
                  SELECT [ID] id, [Year], [Amount]
                    FROM [localTest].[dbo].[Years]
            ) x pivot (
                    min([Amount])
                    for [Year] IN ('+@cols+')
            ) p ) as b on a.[ID] = b.id';
EXECUTE(@Sql);

答案 1 :(得分:0)

将第二次查询的结果插入到#temp表中,并将#temp表联接到main表中,如下所示:

    SELECT [id]
      ,[title]
      ,[desc]
  FROM [localTest].[dbo].[main];


DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)
select @cols  = STUFF((SELECT distinct ',' + QUOTENAME([Year]) from [localTest].[dbo].[Years] FOR XML PATH(''),TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
    set @query = 'SELECT [ID], ' + @cols + ' from (select [ID], [Year], [Amount] FROM [localTest].[dbo].[Years] ) x pivot (min([Amount]) for [Year] in (' + @cols + ')) p '

insert into #temp
execute(@query);

select * from [localTest].[dbo].[main]  AS  a inner join #temp as b on a.id = b.id