sql >> Database >  >> RDS >> Sqlserver

SQL Server PIVOT met meerdere X-as kolommen

Ok, zoals je al zei, je hebt dynamische SQL nodig, dus ga eerst naar deze link . Als je dat eenmaal hebt gelezen, probeer dan het volgende:

GE-UPDATE CODE VOLGENDE OPMERKING:

DECLARE @cols AS NVARCHAR(MAX), @cols2 AS NVARCHAR(MAX), @query AS NVARCHAR(MAX);

WITH CTE AS
(
    SELECT *, CAST([Year] AS NVARCHAR(4))+RIGHT('00'+CAST([Month] AS NVARCHAR(2)),2) YearMonth
    FROM YourTable
)

SELECT @cols = STUFF((  SELECT DISTINCT ',' + QUOTENAME(YearMonth) 
                        FROM CTE 
                        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,''),
       @cols2 = STUFF(( SELECT DISTINCT ',ISNULL(' + QUOTENAME(YearMonth) + ',0) AS ' + QUOTENAME(YearMonth)
                        FROM CTE 
                        FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')


SET @query = '
SELECT Payroll, Forname, Surname, ' + @cols2 + '
FROM (  SELECT  Payroll, Forname, Surname, 
                CAST([Year] AS NVARCHAR(4))+RIGHT(''00''+CAST([Month] AS NVARCHAR(2)),2) YearMonth,
                Amount
        FROM YourTable ) T
PIVOT(SUM(Amount) FOR YearMonth IN ('[email protected]+')) PT'

EXEC(@Query)


  1. Django 1.8 Migratie met Postgres BDR 9.4.1

  2. Hoe converteer ik deze MySQL-verklaring naar symfony Propel?

  3. Fout tijdens installatie - Database-initialisatie mislukt

  4. Google Chart Tools met PHP &MySQl