sql >> Base de Datos >  >> RDS >> Sqlserver

SQL Server 2005:datos dinámicos sin suma/recuento y lista dinámica de valores

Esto se acerca a lo que buscas. También he incluido un script de creación de tablas y datos de muestra para que otros los usen. La inspiración para esta solución provino de aquí

-- Dynamic PIVOT
DECLARE @T AS TABLE(y INT NOT NULL PRIMARY KEY);

DECLARE
@cols AS NVARCHAR(MAX),
@y    AS INT,
@sql  AS NVARCHAR(MAX);

-- Construct the column list for the IN clause
-- e.g., [Dog],[Python]
SET @cols = STUFF(
(SELECT N',' + QUOTENAME(y) AS [text()]
FROM (SELECT DISTINCT [Value] AS y FROM dbo.table_1) AS Y
ORDER BY y
FOR XML PATH('')),
1, 1, N'');

-- Construct the full T-SQL statement
-- and execute dynamically
SET @sql = N'SELECT *
FROM (SELECT *
FROM dbo.table_1) AS D
PIVOT(MIN(value) FOR value IN(' + @cols + N')) AS P;';

PRINT @sql
EXEC sp_executesql @sql;
GO

Creación de tablas:

CREATE TABLE [dbo].[Table_1](
    [Name] [varchar](50) COLLATE Latin1_General_CI_AS NULL,
    [Value] [varchar](50) COLLATE Latin1_General_CI_AS NULL
) ON [PRIMARY]

GO

Datos de muestra:

insert into dbo.table_1 values ('John','Dog')
insert into dbo.table_1 values ('John','Cat')
insert into dbo.table_1 values ('John','Fish')
insert into dbo.table_1 values ('Bob ','Python')
insert into dbo.table_1 values ('Bob ','Camel')