I want to generate SQL query output like screenshot - sql

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.

Related

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 pivot query dynamically

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

SQL Dynamic SELECT statement from values stored in a table

I have been researching this for a couple of days and feel like I am going around in circles. I have basic knowledge of SQL but there are many areas I do not understand.
I have a table that stores the names and fields of all the other tables in my database.
tblFields
===================================================
TableName FieldName BookmarkName
---------------------------------------------------
Customer FirstName CustomerFirstName
Customer LastName CustomerLastName
Customer DOB CustomerDOB
I want to write a SELECT statement like the following but i am unable to get it work:
SELECT (SELECT [FieldName] FROM [TableName]) FROM tblFields
Is this possible? The application I have developed requires this for user customization of reports.
If i understand what you are trying to do, i think this will help you. It is not pretty and it works for SQL Server 2005 and above, but maybe this is what you are looking for:
declare #tableName nvarchar(100)
declare #sqlQuery nvarchar(max)
declare #fields varchar(500)
set #tableName = 'YourTableName'
set #fields = ''
select #fields = #fields + QUOTENAME(t.fieldname) + ',' from (
select distinct fieldname from tblfields where tablename = #tableName)t
set #sqlQuery = 'select ' + left(#fields, LEN(#fields)-1) + ' from ' + QUOTENAME(#tableName)
execute sp_executesql #sqlQuery
Edit: As Martin suggested, i edited so that the columns and tablename are using QUOTENAME
If I understand correctly what you are trying to do, you are probably better off doing this as two separate queries from your program. One which gets the fields you want to select which you then use in your program to build up the second query which actually gets the data.
If it must be done entirely in SQL, then you will need to tell us what database you are using. If it is SQL Server, you might be able to user a cursor over the first query to build up the second query which you then execute with the sp_executesql stored procedure. But doing doing it outside of SQL would be recommended.

t-sql string & table column manipulation

DETAILS table has following columns
Title First Second Third Fourth Fifth
------------------------------------------
A null null null null null
input variable
--------------
#columns = 'Title, Third, Fourth'
I want to generate ouput as
#allcolumns = 'Title, Third, Fourth, First, Second, Fifth'
Variable #allcolumns will contain all columns from DETAILS table but with #columns first and then the remaining columns
So for instance if
#columns = 'Title, Fourth,Fifth'
then output will be
#allcolumns = 'Title, Fourth, Fifth, First, Second, Third'
Thanks
This should work:
DECLARE #columns VARCHAR(max);
DECLARE #allcolumns VARCHAR(max);
SET #columns = 'Title,Fourth,Fifth';
SET #allcolumns = #columns;
SELECT #allcolumns = #allcolumns + ',' + column_name FROM
INFORMATION_SCHEMA.columns WHERE
table_name = 'DETAILS' AND
CHARINDEX(column_name, #columns) = 0;
SELECT #allcolumns;
GO
An additional thought: if you want to create a SELECT statement to select the columns in the order generated by the above code, you could do this:
DECLARE #sql VARCHAR(max);
SET #sql = 'SELECT ' + #allcolumns + ' FROM DETAILS';
EXEC(#sql);
...although I can't see why you would want to do that.
There are many ways to do this. Being your question is rather general, I would suggest looking at the following link and using your INFORMATION_SCHEMA views if using SQL Server.
http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/
First and most importantly, why not simply return columns First through Fifth and let the calling code determine which columns to use? The SQL language in general was not designed for dynamic column determination and generation. It presumes that the calling code handles the determination of the columns that should be returned. Further, calling code should never depend on the column order in a query and therefore the order of the columns in the output should make no difference. Given that, you should do this type of manipulation in a middle-tier component or reporting tool.
Second, while it is possible to solve this type of problem in T-SQL, it should not be done. T-SQL is awful for string manipulation.
Lastly, if this is the type of query you need to build to get the proper information from your database schema, you might need to re-evaluate your database schema. When you start running into more and more complicated queries in order to retrieve the information you want, it is indicative of a schema that is out of touch with the business needs.