I have the following table with some details as shown below:
Example:
Creating table product:
create table product
(
slno int,
item nvarchar(20)
);
Inserting some records:
insert into product values(1,'HDD');
insert into product values(2,'PenDrive');
insert into product values(3,'RAM');
insert into product values(4,'DVD');
insert into product values(5,'RAM');
insert into product values(6,'HDD');
Table product contains:
select * from product;
slno item
----------
1 HDD
2 PenDrive
3 RAM
4 DVD
5 RAM
6 HDD
Now I want make a string of items for which i have written the following script:
select distinct
(
select distinct item+','
from product
FOR XML PATH('')
) temp
from product;
Result is:
temp
----------------------
DVD,HDD,PenDrive,RAM,
Note: Now I want to show the result in the following format: (In which I need to use the pivot table with the above query and need to display how many product have sold out).
DVD HDD PenDrive RAM
-----------------------
1 2 1 2
My Try:
select DVD,HDD,PenDrive,RAM
from
(
select distinct
(
select distinct item+','
from product
FOR XML PATH('')
) temp
from product
) as a
pivot
(
count(temp)
for temp in(DVD,HDD,PenDrive,RAM)
) pt
But getting result :
DVD HDD PenDrive RAM
------------------------
0 0 0 0