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

use los valores seleccionados de sql como nombres de fila para otra selección

Para SQL Server 2005+, puede usar SQL dinámico y PIVOT .

DECLARE @ValuesNames NVARCHAR(4000), @Query NVARCHAR(MAX)
SET @ValuesNames = ''

SELECT @ValuesNames = @ValuesNames + QUOTENAME([name]) + ','
FROM [values] A
INNER JOIN value_type B
ON B.value_id = A.id
GROUP BY [name]
ORDER BY [name]

SET @ValuesNames = LEFT(@ValuesNames,LEN(@ValuesNames)-1)

SET @Query = '
SELECT [date], '[email protected]+'
FROM (  SELECT [date], [name], value
        FROM [values]
        LEFT JOIN value_type ON value_id = id) A
PIVOT(SUM(value) FOR [name] IN ('[email protected]+')) AS PT
'
EXEC sp_executesql @Query