SQL Pivot function error

1

First question: The column that will be transformed into Line (in this case specific the header) can be repeated? I have several records that repeat, Example Column Description :

I'm trying to do this:

IF object_id('tempdb..#tab1') IS NOT NULL 
begin
    drop table #tab1
end

go

create table #tab1(
Id int null,
Nome varchar(50) null,
CNPJ varchar(50) null,
Descricao varchar(50) null,
Situacao varchar(50) null
)

insert into #tab1 (Id, Nome, CNPJ, Descricao, Situacao) values (1,'Empresa1','8439659000150','Descricao1','Positivo')
insert into #tab1 (Id, Nome, CNPJ, Descricao, Situacao) values (1,'Empresa1','8439659000150','Descricao2','Regular')
insert into #tab1 (Id, Nome, CNPJ, Descricao, Situacao) values (1,'Empresa1','8439659000150','Descricao3','Irregular')
insert into #tab1 (Id, Nome, CNPJ, Descricao, Situacao) values (2,'Empresa2','8439659000231','Descricao1','Positivo')
insert into #tab1 (Id, Nome, CNPJ, Descricao, Situacao) values (2,'Empresa2','8439659000231','Descricao2','Regular')
insert into #tab1 (Id, Nome, CNPJ, Descricao, Situacao) values (2,'Empresa2','8439659000231','Descricao3','Irregular')
insert into #tab1 (Id, Nome, CNPJ, Descricao, Situacao) values (3,'Empresa3','11594952000105','Descricao1','Positivo')
insert into #tab1 (Id, Nome, CNPJ, Descricao, Situacao) values (3,'Empresa3','11594952000105','Descricao2','Regular')

SET NOCOUNT ON

DECLARE @COLUNAS VARCHAR(MAX)
SET @COLUNAS = ''

SELECT @COLUNAS = COALESCE(@COLUNAS + '[' + (CAST(Descricao AS NVARCHAR(255))) + '],','')
FROM (SELECT DISTINCT Descricao FROM #tab1) AS DADOS_HORIZONTAIS
SET @COLUNAS = LEFT (@COLUNAS, LEN(@COLUNAS)-1)

DECLARE @SQLSTRING NVARCHAR(500);

SET @SQLSTRING = N'
SELECT * FROM(SELECT Id, Nome, CNPJ, Descricao, Situacao FROM #tab1) AS DADOS_HORIZONTAIS
PIVOT(Situacao FOR Descricao IN('+@COLUNAS+')) AS PivotTable;'

 EXECUTE SP_EXECUTESQL @SQLSTRING

Another problem that occurs error:

Mensagem 156, Nível 15, Estado 1, Linha 13
Sintaxe incorreta próxima à palavra-chave 'FOR'.
    
asked by anonymous 09.05.2017 / 18:22

1 answer

1

The aggregation function is missing

You need to define at least one aggregate function for PIVOT .

Example:

SET @SQLSTRING = N'
SELECT * FROM(SELECT Id, Nome, CNPJ, Descricao, Situacao FROM #tab1) AS DADOS_HORIZONTAIS
PIVOT(MIN(Situacao) FOR Descricao IN('+@COLUNAS+')) AS PivotTable;'
    
09.05.2017 / 18:58