sql >> Database >  >> RDS >> Sqlserver

Drie kolommen SQL PIVOT

Probeer zoiets als dit:

DECLARE @myTable AS TABLE([ID] INT, [Field] VARCHAR(20), [Value] VARCHAR(20))
INSERT INTO @myTable VALUES ('1', 'year', '2011')
INSERT INTO @myTable VALUES ('1', 'month', 'August')
INSERT INTO @myTable VALUES ('2', 'year', '2009')
INSERT INTO @myTable VALUES ('1', 'day', '21')
INSERT INTO @myTable VALUES ('2', 'day', '31')
INSERT INTO @myTable VALUES ('2', 'month', 'July')
INSERT INTO @myTable VALUES ('3', 'year', '2010')
INSERT INTO @myTable VALUES ('3', 'month', 'January')
INSERT INTO @myTable VALUES ('3', 'day', NULL)

SELECT [ID], [year], [month], [day]
FROM
(
      SELECT [ID], [Field], [Value] FROM @myTable
) t
PIVOT
(
    MIN([Value]) FOR [Field] IN ([year], [month], [day]) 
) AS pvt
ORDER BY pvt.[year] DESC

Wat resultaten oplevert van:

ID  year    month   day
1   2011    August  21
3   2010    January NULL
2   2009    July    31


  1. Hulp bij het oplossen van problemen met SqlException:time-out is verlopen bij verbinding, in een niet-belaste situatie

  2. Is het veilig om strings te vergelijken met 'groter dan' en 'kleiner dan' in MySQL?

  3. Gezamenlijke posities rangschikken in MySQL

  4. T-SQL trim   (en andere niet-alfanumerieke tekens)