I have the sample device table and data below. I am trying to find a way to transpose or pivot the rows into columns, while adding more devices (rows) and more attributes (columns) over time, while keeping the query intact but I couldn't find a good way to do this. Using SQL Server 2019. (Also wondering if JSON format is a better storage format for what I want to do?)
Desired Output:
iPad 2021 iPad mini 2021 ......
price 329.00 499.00
Releasedate 2011-09-14 2011-09-14
ScreenSize 10.2 8.3
ScreenResolutionWidth 1620 1488
ScreenResolutionHeight 2160 2266
.....
The values for the attributes can be numeric, string, date, boolean or null.
SQL to create the table and data:
CREATE TABLE [device](
[id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](100) NULL,
[price] [decimal](18, 2) NULL,
[Releasedate] [date] NULL,
[ScreenSize] [decimal](18, 1) NULL,
[ScreenResolutionWidth] [int] NULL,
[ScreenResolutionHeight] [int] NULL
)
SET DATEFORMAT ymd
INSERT INTO [device] (Name, price, Releasedate, ScreenSize, ScreenResolutionWidth, ScreenResolutionHeight) VALUES
('iPad 2021', 329.00, CONVERT(DATETIME, '2011-09-14', 120), 10.2, 1620, 2160),
('iPad mini 2021', 499.00, CONVERT(DATETIME, '2021-09-14', 120), 8.3, 1488, 2266)