I have a database table "table_name1" in SQL Server 2012 created using:
CREATE TABLE table_name1 (
created_date date,
complete_hour int,
col_percent float
);
INSERT INTO table_name1 values
('2017-06-14', 8, 0.3),
('2017-06-14', 9, 1.96),
('2017-06-14', 10, 3.92),
('2017-06-07', 8, 0.17),
('2017-06-07', 9, 2.87),
('2017-06-07', 10, 3.72),
('2017-05-31', 7, 0.14),
('2017-05-31', 8, 0.72),
('2017-05-31', 9, 3.77),
('2017-05-31', 10, 5.8);
What I want to do is get result like:
created_date col1 col2 col3 col4
2017-06-14 BLANK 0.3 1.96 3.92
2017-06-07 BLANK 0.17 2.87 3.72
2017-05-31 0.14 0.72 3.77 5.8
I tried using pivot and as the number of rows in table_name1 will keep changing I think I'll have to use dynamic sql. So I tried using the answer from Efficiently convert rows to columns in sql server post but unable to tweak it to solve my problem. There are 3 columns instead of two that I need to consider and have to group by created_date as well.
Can I get some suggestions on how to do this?
EDIT: Little modified version of answer I am trying to follow is:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT ',' + QUOTENAME(col_percent)
from table_name1
group by created_date, complete_hour, col_percent
order by complete_hour
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = N'SELECT ' + @cols + N' from
(
select created_date, col_percent
from table_name1
) x
pivot
(
max(created_date)
for col_percent in (' + @cols + N')
) p '
exec sp_executesql @query;
And it gives result as:
0.14 0.72 0.17 0.3 3.77 2.87 1.96 5.8 3.72 3.92
2017-05-31 2017-05-31 2017-06-07 2017-06-14 2017-05-31 2017-06-07 2017-06-14 2017-05-31 2017-06-07 2017-06-14
I know I am doing it wrong to get my desired output, but when I try to change column names in the pivot, I get or some other changes I get either "invalid column name" or "The incorrect value "0.14" is supplied in the PIVOT operator."