How to use pivot query dynamically - sql

I have here a query: (this was modified. thank you SO for the help) and I'm using mssql 2008
SELECT 'Risk','ADAB','Bahrain','Kuwait','Masirah','Qatar' <-- fixed
UNION ALL
select CONVERT(VARCHAR,risk)
,CONVERT(VARCHAR,[ADAB]) as ADAB <-- fixed
,CONVERT(VARCHAR,[Bahrain]) as Bahrain <-- fixed
,CONVERT(VARCHAR,[Kuwait]) as Kuwait <-- fixed
,CONVERT(VARCHAR,[Masirah]) as Masirah <-- fixed
,CONVERT(VARCHAR,[Qatar]) as Qatar <-- fixed
from (select risk, piv_site = risk, site
from qcvqciffull
where (1=1) AND Risk is not null) as ps
pivot (count(piv_site)
for site in ([ADAB], [Bahrain], [Kuwait], [Masirah], [Qatar])) as pvt <-- fixed
I have here a fiddle. Is it possible to turn those fields who have "fixed" text beside it and turn them dynamically? Say, I have a new record coming in, USA for instance. Is there a way for it?
Any help would be much appreciated. Thanks.

For current scenerio, you have to add whatever text will add other than this.
Or
you can go for dynamic pivot which automatically find and create column, where you have to create dynamic query and then execute.
Refer this :- Dynamic Pivot
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName= ISNULL(#ColumnName + ',','')
+ QUOTENAME(Course)
FROM (SELECT DISTINCT Course FROM #CourseSales) AS Courses
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT Year, ' + #ColumnName + '
FROM #Tablename
PIVOT(SUM(Earning)
FOR Course IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery

Related

I want to generate SQL query output like screenshot

I am getting data like below screenshot using select VendorShortName,BasePrice,convert(varchar, ModifiedDate,101) as date from prices where barcode='8712566383849'
Now for generating the graph, I need data like below screenshot.
Can anyone help me?
You can easily do this by using PIVOT. Here is example how you will get that. Firt Image will show you simple PIVOT Query and how you achieve that.
Second Image Will show you dynamic Query generation - which might be more helpful as based on your image it seems you require to generate dynamic columns
so please refer second image for the same.
Based on query i have created below snippet - see if it helps you.
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName= ISNULL(#ColumnName + ',','')
+ QUOTENAME(vendorshortname)
FROM (select distinct vendorshortname from Prices) AS Prices
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT ModifiedDate, ' + #ColumnName + '
FROM (select VendorShortName,BasePrice,ModifiedDate from prices where barcode=''8712566383849'') As SourceTable
PIVOT
(avg(BasePrice)
FOR VendorShortName IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery
Depending on the type of database, PIVOT is what you use in these cases. You will need to know the values of V1, V2 etc. or do dynamic SQL.
Traditionally though, this kind of manipulation is done at the client (graphing) side, not on the database because, as you are discovering, that transformed data is not a good fit to the relational model.

Dynamic pivot inside procedure (SQL Server 2008) no fields on SSRS

I have a problem with find solution on how to put inside procedure 3 different dynamic pivot query (example below) and use it in SSRS where I can't add datasets, there are no fields. Another important thing is that at the beginning of my procedure I have one parameter "#Data_x" as the date when I am trying to ad datasets there is an info: "Define Query Parameters" and on the list is only "#Data_x" which I can't define "manually".
Here is example of dynamic pivot:
DECLARE #PmtCols AS NVARCHAR(MAX), #query_ppl AS NVARCHAR(MAX)
select #PmtCols = STUFF((SELECT ',' + QUOTENAME(number)
from #data
group by number
order by number
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')
if OBJECT_ID ('tempdb..##ready') is not null drop table ##ready
set #query = 'SELECT ID,' + #PmtCols + ' into ##ready from
(select number, ID, przerwa_pl from #data) as x
PIVOT
(max(przerwa_pl) for number in (' + #PmtCols + ')) as p'
execute(#query) ;
I tried to function FMTONLY OFF/ON but still nothing. What can I do, please help?

How to return data from stored procedure in a view SQL Server 2008

So i have this code:
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName= ISNULL(#ColumnName + ',','')
+ QUOTENAME(period)
FROM (SELECT DISTINCT period FROM atbv_Accounting_OrdersDeliveries WHERE InvoiceNo IS NOT NULL) AS Periods
SET #DynamicPivotQuery =
N'SELECT ' + #ColumnName + '
FROM (SELECT
ArticleID, period, SUM(Amount) As Total
FROM atbv_Accounting_OrdersDeliveries
WHERE InvoiceNo IS NOT NULL
GROUP BY ArticleID, period
) AS T
PIVOT(SUM(TOTAL)
FOR period IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery
I saved in i a stored procedure as i cannot declare variables in a view. Is there a way to call this procedure in a view? Note that column amount is dynamic as well :)
Thanks!
Try to use the Stored Procedure instead of a view.
If that isn't possible for any reason, you can create a SQL Server Agent Job that periodically fills a table using a stored procedure and the client than uses the "cached" data.
You can't have a dynamic view, what would be the point?
If you want to know how to share data from stored procedures then
How to Share Data between Stored Procedures
is a great text. If you want to understand dynamic SQL then I recommend
The Curse and Blessings of Dynamic SQL
by the same author, Erland Sommarskog. Both topics are too expansive for a simple answer on Stack Overflow.

Dynamic PIVOT query - How to save it in SQL Server?

I had to built a dynamic PIVOT in SQL Server as described in this article using the following script:
DECLARE #DynamicPivotQuery AS NVARCHAR(MAX)
DECLARE #ColumnName AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT #ColumnName= ISNULL(#ColumnName + ',','')
+ QUOTENAME(Course)
FROM (SELECT DISTINCT Course FROM #CourseSales) AS Courses
--Prepare the PIVOT query using the dynamic
SET #DynamicPivotQuery =
N'SELECT Year, ' + #ColumnName + '
FROM #CourseSales
PIVOT(SUM(Earning)
FOR Course IN (' + #ColumnName + ')) AS PVTTable'
--Execute the Dynamic Pivot Query
EXEC sp_executesql #DynamicPivotQuery
It works great and it returns a dynamic table as expected.
However, I would like to be able to select it in an other query but can not find a proper way to do so:
A view does not work as it does not accept variables
A table valued function does not work as I don't know in advance the structure of the output table
A stored procedure does not work as I can not use it in a SELECT query
What would be the best solution to save this dynamic pivot query and be able to SELECT it afterwards?
Thank you
Sylvain
Oh. You can use temp table, my friend. The first, check the exists of temp table. And remember drop it at the end of query.
You could try to use the stored procedure and in that sp use the SELECT INTO in the dynamic pivot query and store in a temporary table (#myDynamicPivot).
Then you can use the temporary table in your next selects statements. Make sure you drop your table after using it.
Edit
I would consider moving that data that the pivot table is created against to a data warehouse and create an analysis database over it. This way you can query using the dimensions and the data will be much faster and it will be more optimized for storage and query.

How to use the result of a SUBSTRING as column definition in an INSERT INTO query?

I need to dynamically create INSERT INTO statements with column definition, to prevent IDENTITY_INSERT problems. I already found out how to retrieve the column-list of tables and also a way, to put it all together.
DECLARE #Query nvarchar(4000)
DECLARE #columnlist nvarchar(4000)
// Result of this query e.g.: "[cid], [pid], [nid], [uid], [subject]"
SET #columnlist = (SELECT SUBSTRING((SELECT ', ' + QUOTENAME(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'from_table' ORDER BY ORDINAL_POSITION FOR XML path('')), 3, 200000))
SET #query ='INSERT INTO to_table (' + #columnlist + ') SELECT ' + #columnlist + ' FROM from_table;'
exec sp_executesql #query
Anyways i don't feel comfortable with this solution, because i am building a string, which gets executed afterwards. I am looking for a solution with a query, that executes directly. Any suggestions?
Dynamic SQL really is your only option and it can be safe and reliable if you use good practices like always using quotename(). The only other gotcha is if the query grows over 4000 characters in which case you should use nvarchar(max) and use exec (#query) instead of sp_executesql.