I'm writing a query where there is pivot table that has to generated. Right now below is my code.
select *
from
(select [case owner], [time taken(minutes)] from StatusTable) as pivotdata
pivot(
sum([time taken(minutes)])
for [CASE OWNER] in
("XXX", "AAA", "BBB")
) as pivoting
But instead of giving the rows in for-in
, I need to get this dynamically, I've seen a query here SQL Server dynamic PIVOT query? And modified my query to be
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME([case owner])
FROM StatusTable c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'select *
from
(select [case owner], [time taken(minutes)] from StatusTable) as pivotdata
pivot(
sum([time taken(minutes)])
for [CASE OWNER] in
('+@cols+')
) as pivoting'
execute(@query)
And this is working fine, but the problem is that I've to use this query in my JDBC program. And without using execute(@query)
, it is not running in my SQL Server. Can I make this query similar to the first query, so that I can use the same in my program?