martes, 4 de febrero de 2025

Usando PIVOT no SQL Server


Olá pessaol, bem vindo ao blog DICAS-SQL.



A dica de hoje é para mostrar a operação do operador relacional PIVOT



Você pode usar os operadores relacionais PIVOT e UNPIVOT para alterar uma expressão com valor de tabela para outra tabela



 create table #vendas(
  id                   int identity(1,1),
  data              datetime not null,
  codigo          char(3),
  cantidade     int
)

--#vendas dos últimos 3 dias
insert into #vendas values(getdate()-3, 'A01', 100)
insert into #vendas values(getdate()-3, 'A02', 90)
insert into #vendas values(getdate()-3, 'A03', 90)
insert into #vendas values(getdate()-2, 'A01', 120)
insert into #vendas values(getdate()-2, 'A02', 80)
insert into #vendas values(getdate()-2, 'A03', 70)
insert into #vendas values(getdate()-1, 'A01', 115)
insert into #vendas values(getdate()-1, 'A02', 60)
insert into #vendas values(getdate()-1, 'A03', 50)


--#vendas dos últimos 3 dias
select * from #vendas;



-- LISTA DE BANDAGENS DIÁRIAS  COM UMA COLUNA (CAMPO) POR CODIGO DE PRODUTO
select  PT.* FROM #vendas
pivot (
      sum (cantidade) for codigo in ("A01", "A02", "A03")
)  pt    



-- RESUMO DIARIO
SELECT convert(date, data) as data, sum(A01) as Total_A1, sum(A02) as Total_A2, sum(A03) as Total_A3
FROM (
    -- OU IGUAL À CONSULTA ANTERIOR
    select  PT.* FROM #vendas
    pivot (
      sum (cantidade) for codigo in ("A01", "A02", "A03")
    ) pt    
) A
GROUP BY convert(date, data)

Na proxima va UNPIVOT

No hay comentarios:

Publicar un comentario

Usando PIVOT no SQL Server

Olá pessaol, bem vindo ao blog DICAS-SQL. A dica de hoje é para mostrar a operação do operador relacional PIVOT Você pode usar os operado...