In trying to achieve a Pivot
-ed goal for a two row data table into one row, my first thought was to use a Cross Apply
. By using the Cross Apply
one can identify/generate each of the rows with a specific column name derived from the row's unique id. (e.g. 'Lat1' and 'Lat2 for a 'Latitude' source column).
All is fine when I use INT
or FLOAT
data types but when I try to use a DateTime
all VALUES
become DateTime
.
Example Shipping Lat/Long/DateTime
We have two points in a ships journey reported on two different days:
CREATE TABLE #Shipping
(
[RouteID] [INT] NOT NULL,
[Latitude] FLOAT NOT NULL,
[Longitude] FLOAT NOT NULL,
[Time] DATETIME NOT NULL
);
INSERT #Shipping(RouteID, [Latitude], [Longitude], [Time])
VALUES (1, 18.0221, -63.1206, '24-Jan-2016'),
(2, 17.8353, -62.99667, '25-Jan-2016');
Successful CrossApply
If we use CrossApply
against the data for the first three columns
SELECT col+cast([RouteID] as varchar(1)) new_col
, X.value
FROM #Shipping
CROSS APPLY
(
VALUES
(RouteID, 'Id')
, (Latitude, 'Lat')
, (Longitude, 'Lon')
) X (value, col)
Our results are as expected:
Great!
Failure CrossApply With DateTime
But once we add DateTime
to the mix:
SELECT col+cast([RouteID] as varchar(1)) new_col
, X.value
FROM #Shipping
CROSS APPLY
(
VALUES
(RouteID, 'Id')
, (Latitude, 'Lat')
, (Longitude, 'Lon')
, ([Time], 'Time')
) X (value, col)
All become DateTime
s
How should one work around this if my end goal is to pivot all the values from the original table into one row?