How can this query be written dynamically without declaring a variable for the categories so it would be possible to make an view?
This is a rephrase of my last question with a reproducible example:
CREATE TABLE dbo.tableName
(
category varchar(300),
product varchar(300),
date_time varchar(300),
end_value varchar(300)
);
INSERT INTO tableName (category,product,date_time,end_value) VALUES ('Site Furnishings', 'RX', '09/01/2021', '1,87');
INSERT INTO tableName (category,product,date_time,end_value) VALUES ('Site Furnishings', 'RX', '10/01/2021', '29,83');
INSERT INTO tableName (category,product,date_time,end_value) VALUES ('Site Furnishings', 'RX', '13/01/2021', '1,12');
INSERT INTO tableName (category,product,date_time,end_value) VALUES ('Site Furnishings', 'RX', '14/01/2021', '52,99');
INSERT INTO tableName (category,product,date_time,end_value) VALUES ('Site Furnishings', 'RX', '26/01/2021', '0,73');
INSERT INTO tableName (category,product,date_time,end_value) VALUES ('Granite Surfaces', 'V50', '09/01/2021', '1,13');
INSERT INTO tableName (category,product,date_time,end_value) VALUES ('Granite Surfaces', 'V50', '10/01/2021', '25,72');
INSERT INTO tableName (category,product,date_time,end_value) VALUES ('Granite Surfaces', 'V50', '26/01/2021', '3,95');
INSERT INTO tableName (category,product,date_time,end_value) VALUES ('Granite Surfaces', 'V50', '14/02/2021', '2,43');
INSERT INTO tableName (category,product,date_time,end_value) VALUES ('Glass & Glazing', 'Jetta', '09/01/2021', '92,65');
INSERT INTO tableName (category,product,date_time,end_value) VALUES ('Glass & Glazing', 'Jetta', '17/01/2021', '1,19');
INSERT INTO tableName (category,product,date_time,end_value) VALUES ('Glass & Glazing', 'Jetta', '18/01/2021', '1,19');
SELECT STUFF(
(SELECT DISTINCT ',' + QUOTENAME(category)
FROM dbo.tablename
FOR XML PATH (''),
TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
Results in this: [Glass & Glazing],[Granite Surfaces],[Site Furnishings] which I use for my next query:
SELECT date_time, [Glass & Glazing],[Granite Surfaces],[Site Furnishings]
FROM (
SELECT date_time, end_value, category
FROM dbo.tablename
) x
pivot
(
max(end_value)
for category in ([Glass & Glazing],[Granite Surfaces],[Site Furnishings])
) p
How can this query be written dynamically without declaring a variable for the columns so it would be possible to make an view?