This is my current table data:
Godown_Column | Product_Column | Quantity |
---|---|---|
Godown 1 | Product 1 | 10 |
Godown 1 | Product 2 | 20 |
Godown 2 | Product 3 | 30 |
Godown 3 | Product 3 | 40 |
Here, Godowns_Columns
has unlimited number of rows with different godowns.
How do I write a SQL query to get this result:
Product_Col | Godown 1 | Godown 2 | Godown 3 |
---|---|---|---|
Product 1 | 10 | ||
Product 2 | 20 | ||
Product 3 | 30 | 40 |
You can use dynamic pivot since number of godowns is unknown.
Schema:
create table mytable(Godown_Column varchar(50), Product_Column varchar(50), Quantity int)
insert into mytable values('Godown 1', 'Product 1' ,10);
insert into mytable values('Godown 1', 'Product 2' ,20);
insert into mytable values('Godown 2', 'Product 3' ,30);
insert into mytable values('Godown 3', 'Product 3' ,40);
Query:
DECLARE @cols AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';
SET @cols = STUFF((SELECT distinct ',' + quotename(Godown_Column)
FROM mytable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT Product_Column,' + @cols + '
from
(
select * from mytable
) x
pivot
(
sum(quantity)
for Godown_Column in (' + @cols + ')
) p'
execute(@query)
Output:
Product_Column | Godown 1 | Godown 2 | Godown 3 |
---|---|---|---|
Product 1 | 10 | null | null |
Product 2 | 20 | null | null |
Product 3 | null | 30 | 40 |
db<fiddle here