Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

usa i valori sql selezionati come nomi di riga per un'altra selezione

Per SQL Server 2005+, puoi utilizzare SQL dinamico e 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