I have a pivot query from pivoted table*(a dynamic columns)*, my problem is I want to copy/clone the pivot result into new_table. Which is I don't know how to do it,
Query:
DECLARE #cols NVARCHAR(MAX), #query NVARCHAR(MAX);
SET #cols = STUFF((SELECT DISTINCT','+QUOTENAME(c.ReportedDate)
FROM dbo.Activity c FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '');
SELECT #query = 'SELECT * FROM (SELECT b.Description, CONVERT(VARCHAR(10), reportedDate, 120) as reportedDate,Status
FROM Activity left join ActivityType b on b.activityTypeId = Activity.ActivityTypeId )
AS t PIVOT ( COUNT(reportedDate) FOR reportedDate IN( ' + #cols + ' )' + ') AS p ;'
EXECUTE (#query);
How to achieve my expectations to get the same result from pivotTable to new_table with the same data result?
You can use a table (or a global temporary table) to store data via select into, so you will able to have access on it.
DECLARE #cols NVARCHAR(MAX), #query NVARCHAR(MAX);
SET #cols = STUFF((SELECT DISTINCT','+QUOTENAME(c.ReportedDate)
FROM dbo.Activity c FOR XML PATH(''), TYPE).value('.', 'nvarchar(max)'), 1, 1, '');
SELECT #query = 'SELECT * into ##results FROM (SELECT b.Description, CONVERT(VARCHAR(10), reportedDate, 120) as reportedDate,Status
FROM Activity left join ActivityType b on b.activityTypeId = Activity.ActivityTypeId )
AS t PIVOT ( COUNT(reportedDate) FOR reportedDate IN( ' + #cols + ' )' + ') AS p ;'
EXECUTE (#query);
SELECT * FROM ##results
Related
I want to convert Row into column as shown in below Expected result image.
I have a table and getting data as shown Existing Table image.
Designation Column has dynamic value(Number of value is not fix)
I tried:
DECLARE #cols AS NVARCHAR(MAX),#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(designation)
from MyTable
group by designation
order by designation
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),1,1,'')
set #query = N'SELECT ' + #cols + N' from
(
select SanctionStrength , designation from MyTable
) x
pivot
(
max(SanctionStrength) for designation in (' + #cols + N')
) p '
exec sp_executesql #query;
I am getting result as expected but only for SS.
How can i bind value of AS and VAC together.
you need to combine columns before pivot.
DECLARE #cols AS NVARCHAR(MAX),#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT ',' + QUOTENAME(designation)
from MyTable
group by designation
order by designation
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'),1,1,'')
set #query = N'SELECT Row, ' + #cols + N' from
(
select ''SS'' Row, SS AS Value , designation from MyTable
UNION ALL
select ''AS'' Row, [AS] AS Value , designation from MyTable
UNION ALL
select ''Vac'' Row, Vac AS Value , designation from MyTable
) x
pivot
(
max(Value) for designation in (' + #cols + N')
) p '
exec sp_executesql #query;
Columns are not alphabetic because I can't use "order by" with "distinct".Please help me...
My Query :
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT distinct ',MAX(CASE WHEN KullaniciAdi = ''' + p.KullaniciAdi + ''' THEN KisiAdi END) AS ' + QUOTENAME(p.KullaniciAdi)
FROM Populer p FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')
set #query = 'SELECT top 100 ' + #cols + ' FROM ( SELECT KullaniciAdi,KisiAdi,ROW_NUMBER() OVER (PARTITION BY KullaniciAdi ORDER BY EklenmeTarihi) AS RowNum FROM Populer ) x GROUP BY RowNum '
EXECUTE(#query)
Results:
Of course you can. The key is to replace the distinct with group by. Then use order by:
SET #cols = STUFF((SELECT ', MAX(CASE WHEN KullaniciAdi = ''' + p.KullaniciAdi + ''' THEN KisiAdi END) AS ' + QUOTENAME(p.KullaniciAdi)
FROM Populer p
GROUP BY KullaniciAdi
ORDER BY p.KullaniciAdi
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)'
), 1, 1, ''
) ;
One way around this is to make your query a derived table:
SELECT * FROM
(SELECT DISTINCT {the rest of your current query}) t
ORDER BY SomeColumn
Sorry if this isn't the best way to ask this but I am stuck at this point, I have tried researching but to no avail, trying to join these two queries:
SELECT [id]
,[title]
,[desc]
FROM [localTest].[dbo].[main];
DECLARE #cols AS NVARCHAR(MAX), #query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME([Year]) from [localTest].[dbo].[Years] FOR XML PATH(''),TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
set #query = 'SELECT [ID], ' + #cols + ' from (select [ID], [Year], [Amount] FROM [localTest].[dbo].[Years] ) x pivot (min([Amount]) for [Year] in (' + #cols + ')) p '
execute(#query);
Looking for the final result here:
enter image description here
I figured it out, here is my solution:
DECLARE #cols AS NVARCHAR(MAX);
SELECT #cols = STUFF((SELECT distinct ',' + QUOTENAME([Year]) FROM [localTest].[dbo].[Years] FOR XML PATH(''),TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'');
DECLARE #Sql VARCHAR(max);
SELECT #Sql = 'SELECT * FROM [localTest].[dbo].[main] a join (
SELECT * FROM (
SELECT [ID] id, [Year], [Amount]
FROM [localTest].[dbo].[Years]
) x pivot (
min([Amount])
for [Year] IN ('+#cols+')
) p ) as b on a.[ID] = b.id';
EXECUTE(#Sql);
Insert the result of second query to a #temp table and join the #temp table to main table like below:
SELECT [id]
,[title]
,[desc]
FROM [localTest].[dbo].[main];
DECLARE #cols AS NVARCHAR(MAX), #query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME([Year]) from [localTest].[dbo].[Years] FOR XML PATH(''),TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
set #query = 'SELECT [ID], ' + #cols + ' from (select [ID], [Year], [Amount] FROM [localTest].[dbo].[Years] ) x pivot (min([Amount]) for [Year] in (' + #cols + ')) p '
insert into #temp
execute(#query);
select * from [localTest].[dbo].[main] AS a inner join #temp as b on a.id = b.id
I have dynamic sql query as below.
DECLARE #cols AS NVARCHAR(MAX) = '[0],[3],[11]',
#query AS NVARCHAR(MAX)
SET #query = N'SELECT * FROM
(
SELECT
year(createdDate) as [year],month(createdDate) as [month],cp.product_Id as product_ID,cp.salesprice as Amount
FROM customer_products cp
)s
PIVOT
(
SUM(Amount)
FOR product_Id IN ( '+ #cols +' ))
AS pvt;'
EXECUTE(#query)
Question:
Above query works however below query is not working because of
SELECT #cols = CONCAT(#cols, '[', cast(product_ID as varchar),']') FROM Product
code block.Error displays Incorrect syntax near
DECLARE #cols AS NVARCHAR(MAX) = '',
#query AS NVARCHAR(MAX)
SELECT #cols = CONCAT(#cols, '[', cast(product_ID as varchar),'],') FROM Product
SET #query = N'SELECT * FROM
(
SELECT
year(createdDate) as [year],month(createdDate) as [month],cp.product_Id as product_ID,cp.salesprice as Amount
FROM customer_products cp
)s
PIVOT
(
SUM(Amount)
FOR product_Id IN ( '+ #cols +' ))
AS pvt;'
EXECUTE(#query)
Where i miss exactly what is missing in above query while selecting productID from Product ?
You need to remove last , from #cols, add
SET #cols = LEFT(#cols, LEN(#cols) - 1)
You can consider using XML instead CONCAT like:
SELECT #cols = STUFF((SELECT ',' + QUOTENAME(CAST(product_ID as VARCHAR(10)))
FROM Products
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
, 1, 1, '');
It is a good practice to define length for cast(product_ID as varchar(10))
You need to ensure the last comma is removed from the select list, or you're passing an empty value to PIVOT.
Use this:
DECLARE #cols AS NVARCHAR(MAX) = '',
#query AS NVARCHAR(MAX)
SELECT #cols = COALESCE(#cols+', ','') + '[' + cast(product_ID as varchar) + ']' FROM product
SET #query = N'SELECT * FROM
(
SELECT
year(createdDate) as [year],month(createdDate) as [month],cp.product_Id as product_ID,cp.salesprice as Amount
FROM customer_products cp
)s
PIVOT
(
SUM(Amount)
FOR product_Id IN ( '+ #cols +' ))
AS pvt;'
EXECUTE(#query)
SELECT *
FROM (
SELECT [TM_UserID],
[FullName],
[Worked_dte],
[Worked_Hours]
FROM #Reporting_User_Timesheet
WHERE [worked_dte] BETWEEN '2014-04-04'
AND '2014-04-06'
) AS sourceTable
Pivot(sum([Worked_Hours]) FOR [Worked_dte] IN ([2014-04-04], [2014-04-05], [2014-04-06])) AS PivotTable
A shot in the dark, obviously, but here's how I understood your question.
First, you need a calendar table to get the dates for the range:
http://www.dbdelta.com/calendar-table-and-datetime-functions/
After that, construct the needed PIVOT query and execute it dynamically:
declare #range_start date, #range_end date;
select #range_start = '20140404', #range_end = '20140406';
declare #collist nvarchar(max);
SET #collist = stuff((select distinct ',' + QUOTENAME(convert(varchar,date,112))
FROM calendar
WHERE Datue BETWEEN #range_start AND #range_end
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'');
declare #q nvarchar(max);
set #q = '
SELECT *
FROM (
SELECT [TM_UserID],
[FullName],
[Worked_dte],
[Worked_Hours]
FROM #Reporting_User_Timesheet
WHERE [worked_dte] BETWEEN ''' + CONVERT(varchar, #range_start, 112) + '''
AND ''' + CONVERT(varchar, #range_end, 112) + '''
) AS sourceTable
Pivot (
sum([Worked_Hours]) FOR [Worked_dte] IN (' + #collist + ')
) AS PivotTable
';
exec (#q);