I've the following SQL Query
Select Product_Id, [riy] AS [riy],
[eas] AS [eas]
FROM
(SELECT Product_Id, Store_Name, Quantity
FROM [Product_Stock] INNER JOIN Store on Store.Id = [Product_Stock].Stock_Id where Product_Id = 435) ps
PIVOT
(
SUM(Quantity)
FOR Store_Name IN
([riy],[EAST WAREHOUSE - eas])
) AS pvt
it gives the expected result.Giving me total quantity for locations riy and eas.
However, I want to dynamically get the Store names instead of manually specifying them.
this is what I've done.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SELECT #cols = STUFF((SELECT ',' + QUOTENAME([Product_Id])
FROM [Product_Stock]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SELECT #query =
'SELECT Product_Id FROM
(SELECT Product_Id, Store_Name, Quantity
FROM [Product_Stock] INNER JOIN Store on Store.Id = [Product_Stock].Stock_Id where Product_Id = 435) PS
PIVOT
(
SUM(Quantity)
FOR Store_Name in (' + #cols + ')
) AS PVT'
EXEC SP_EXECUTESQL #query
This gives me an error saying The column '638' was specified multiple times for 'PVT'.
How can i solve this problem?
Without knowing your actual data this is a blind flight, but I think you have two issues:
You must use DISTINCT to get each value only once
You are not concatenating the stores names but the IDs of your products
Try this
SELECT #cols = STUFF((SELECT DISTINCT ',' + QUOTENAME([Store_Name])
FROM [Product_Stock]
INNER JOIN Store on Store.Id = [Product_Stock].Stock_Id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
Just make sure the cols are DISTINCT
... STUFF((SELECT DISTINCT ','...
Thanks #Shnugo for pushing me in the right direction. Here's the query I finally ended up using.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
SELECT #cols = STUFF((SELECT DISTINCT ',' + QUOTENAME([Store].Store_Name)
FROM [Store] INNER JOIN Product_Stock ON Product_Stock.Stock_Id = Store.Id
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SELECT #query =
'SELECT Product_Id , ' + #cols + ' from
(SELECT Product_Id, Store_Name, Quantity
FROM [Product_Stock] INNER JOIN Store on Store.Id = [Product_Stock].Stock_Id WHERE Product_Stock.product_id = 435 ) PS
PIVOT
(
SUM(Quantity)
FOR Store_Name in (' + #cols + ')
) AS PVT'
EXEC SP_EXECUTESQL #query
Related
I have query:
SELECT DISTINCT temp.ID,request.RequestTypeID
FROM #MyTempTable6 as temp
JOIN dbo.FingerMachineUsers as fingeruser
ON temp.UserNo = fingeruser.ID
JOIN dbo.AppUsers as appuser
ON appuser.Id = fingeruser.UserId
LEFT JOIN dbo.Requests as request
ON request.UserId = fingeruser.UserId
And result of it:
How can I create table like this:
ID|RequestTypeID1|RequestTypeID2
1 | 4| 5
If you have only two values, then the simplest method is aggregation:
SELECT t.ID, MIN(r.RequestTypeID), MAX(r.RequestTypeID)
FROM #MyTempTable6 t JOIN
dbo.FingerMachineUsers fu
ON t.UserNo = fu.ID JOIN
dbo.AppUsers au
ON au.Id = fu.UserId LEFT JOIN
dbo.Requests r
ON r.UserId = fu.UserId
GROUP BY t.ID;
If you have have a variable number of values that you want to present, then the query is much more complicated.
PIVOT operator could be your best friend, if there are always only 2 values each...
Try this query...
Disclaimer: This code is purely based on this answer. (https://stackoverflow.com/a/10404455/6327676)
DECLARE #cols AS NVARCHAR(max),
#query AS NVARCHAR(max);
SET #cols = Stuff((SELECT DISTINCT ',' + Quotename(stff.requesttypeid)
FROM TableName stff
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)
SET #query = 'SELECT ID, '+ #cols
+ ' FROM (select ID, RequestTypeId FROM TableName) x pivot (MAX(RequestTypeId) FOR RequestTypeId in ('
+ #cols + ')) p'
EXECUTE(#query)
Try this code it will work according to the result you want.
Firstly you need to dump #MyTempTable6 table into #temptable
then set RequestTypeID columns as comma seperated in #colums varible then set the columnname in #Requestcolumns variable,Then use pivot.
DECLARE #colums AS NVARCHAR(max)
DECLARE #Requestcolumns AS NVARCHAR(max)
DECLARE #query AS NVARCHAR(max);
SELECT DISTINCT temp.ID,request.RequestTypeID
into #temptable
FROM #MyTempTable6 as temp
JOIN dbo.FingerMachineUsers as fingeruser
ON temp.UserNo = fingeruser.ID
JOIN dbo.AppUsers as appuser
ON appuser.Id = fingeruser.UserId
LEFT JOIN dbo.Requests as request
ON request.UserId = fingeruser.UserId
SET #colums = Stuff((SELECT DISTINCT ',' +Quotename(tab.RequestTypeID)
FROM #temptable tab
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)
SET #Requestcolumns = Stuff((SELECT DISTINCT ',' +Quotename(tab.RequestTypeID) +' AS ',+Quotename('RequestTypeID'+CONVERT(varchar(100),tab.RequestTypeID))
FROM #temptable tab
FOR xml path(''), type).value('.', 'NVARCHAR(MAX)'), 1, 1, ''
)
SET #query = 'SELECT ID, '+#Requestcolumns
+ ' FROM (select ID, RequestTypeID FROM #temptable) x pivot (MAX(RequestTypeID) FOR RequestTypeID in ('
+ #colums + ')) p'
EXECUTE(#query)
DROP table #temptable
It would be great if you can help me to convert Column into Rows in SQL Table.
Let say, I have 3 columns called:
Employee_ID
Shift_Date
Shift_ID
Currently it come up like this:
Table Like this
I want to appear like that as the result -
Result Table
But I want value in it, can you guys please help. Thanks.
This is a query I wrote but still error:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(shift_date)
from dbo.tbl_Multi_Shift_Employee WHERE Shift_Date BETWEEN CONVERT(DATE, '01/02/2018 00:00:00',103) AND CONVERT(DATE, '28/02/2018 00:00:00',103)
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Employee_ID, total, Department_ID, shift_id, ' + #cols + ' from
(
select count(*) over(partition by t.Employee_ID) total,
s.Department_ID,
t.Employee_ID,
t.shift_id
from dbo.tbl_Multi_Shift_Employee t
inner join dbo.tbl_department s
on t.Department_ID = s.Department_ID
) x
pivot
(
count(shift_id)
for shift_id in (' + #cols + ')
) p '
PRINT #query
execute(#query)
First you must to remove shift_id from primary select because is used as pivot.
Second, change shift_id with shift_date that is the correct column you are using as pivot columns.
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(shift_date)
from dbo.tbl_Multi_Shift_Employee WHERE Shift_Date BETWEEN CONVERT(DATE, '01/02/2018 00:00:00',103) AND CONVERT(DATE, '28/02/2018 00:00:00',103)
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Employee_ID, total, Department_ID, ' + #cols + ' from
(
select count(*) over(partition by t.Employee_ID) total,
s.Department_ID,
t.Employee_ID,
t.shift_id,
t.shift_date
from dbo.tbl_Multi_Shift_Employee t
inner join dbo.tbl_department s
on t.Department_ID = s.Department_ID
) x
pivot
(
count(shift_id)
for shift_date in (' + #cols + ')
) p '
PRINT #query
execute(#query)
I know there are better ways to design the table but this is just an example of what I need
I just can't seem to get the results I'm looking for
Table and data:
Query:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX);
SET #cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(columnType)
FROM [Values]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
SET #query = 'SELECT ' + #cols + ' FROM
(
SELECT value, columnType
FROM [Values]
) x
PIVOT
(
MAX(value)
FOR columnType IN (' + #cols + ')
) p '
EXECUTE(#query)
Result I get:
Results I want
Product Item SubItem
A A A A A A
A A B A A B
B B A NULL
Your query can be easily resolved using joins for two levels:
select v.value as Product, vi.value as Item, vsi.value as Subitem
from [Values] v left join
[Values] vi
on vi.column_type = 'Item' and vi.parent_id = v.id left join
[Values] vsi
on vsi.column_type = 'Sub Item' and vsi.parent_id = v.id
where v.column_type = 'Product';
If you have an unknown number of levels, then you can expand on this query using dynamic SQL.
I have following table:
How to convert the above table into below structure? I tried using pivot table but couldn't get it to work.
You need to have to look up SQL PIVOT.
Check this fiddle
And the code:
SELECT *
FROM
(
SELECT Prodname,
pcode,
Biiledamt
FROM Product
) p
PIVOT
(
SUM (Biiledamt)
FOR Prodname IN ([Prod1],[Prod2],[Prod3],[Prod4])
) AS pvt
If you do not know beforehand the columns then you can check this fiddle which dynamically generates the columns to use.
The code for that is:
DECLARE #cols AS VARCHAR(MAX),
#query AS VARCHAR(MAX)
SET #cols = STUFF((SELECT distinct ',[' + Prodname +']'
FROM Product c
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
,1,1,'')
SET #query =
' SELECT *
FROM
(
SELECT Prodname,
pcode,
Biiledamt
FROM Product
) p
PIVOT
(
SUM (Biiledamt)
FOR Prodname IN (' + #cols + ')
) AS pvt
'
EXEC(#query)
select *
from (
select vtid, convert(date, dtime) as Date from Transaction_tbl where locid = 5
) as vt
pivot (
count(vtid)
for vtid in (select vtid from VType_tbl)
) as pvt
while executing this query am getting error
Incorrect syntax near the keyword 'select'." and Incorrect syntax near
')'.
actually I have one more table,name= Vtype_table , How Can I load all vtid from vtype table in this query? I want to get output depend upon vtid.
Any help greatly appreciated.
Your PIVOT syntax is correct except you are using a SELECT statement inside your PIVOT.
You cannot use a SELECT statement inside the PIVOT IN clause to select column headers. It is required that the columns for the IN clause be known prior to executing the query.
If you are looking to generate a dynamic list of vtid values, then you will need to use dynamic SQL to get the result and the syntax will be similar to the following:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(vtid)
from VType_tbl
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Date, ' + #cols + '
from
(
select vtid, convert(date, dtime) as Date
from Transaction_tbl
where locid = 5
) d
pivot
(
count(vtid)
for vtid in (' + #cols + ')
) p '
execute(#query);
Edit, if you want the type names to appear then you should be able to use the following:
DECLARE #cols AS NVARCHAR(MAX),
#query AS NVARCHAR(MAX)
select #cols = STUFF((SELECT distinct ',' + QUOTENAME(vt_name)
from VType_tbl
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set #query = 'SELECT Date, ' + #cols + '
from
(
select v.vt_name, convert(date, dtime) as Date
from Transaction_tbl t
inner join VType_tbl v
on t.vtid = v.vtid
where locid = 5
) d
pivot
(
count(vt_name)
for vt_name in (' + #cols + ')
) p '
execute(#query)
Note: I am guessing on the column name for VType_tbl