May 1, 2013 at 9:34 pm
Converting one row as one Column is possible using Pivot. But is there any way to convert particular set of rows to one column?
For example, below is the data table
Customer---------------Product-------------Qty
Jain --------------- Mango -------------10
Charlie --------------- Orange--------------5
Rocky --------------- Mango---------------6
Rocky ---------------- Orange---------------3
Expected Result set
Customer---------------Mango---------------Orange---------------Mango and Orange
Jain---------------------10-------------------NULL ---------------------NULL
Charlie------------------NULL-------------------5-----------------------NULL
Rocky-------------------NULL-----------------NULL---------------------- 9
Appreciate any help
* ---- are used for identation purpose only
Thank You 🙂
May 1, 2013 at 9:56 pm
May 1, 2013 at 10:19 pm
gadde (5/1/2013)
Converting one row as one Column is possible using Pivot. But is there any way to convert particular set of rows to one column?For example, below is the data table
Customer---------------Product-------------Qty
Jain --------------- Mango -------------10
Charlie --------------- Orange--------------5
Rocky --------------- Mango---------------6
Rocky ---------------- Orange---------------3
Expected Result set
Customer---------------Mango---------------Orange---------------Mango and Orange
Jain---------------------10-------------------NULL ---------------------NULL
Charlie------------------NULL-------------------5-----------------------NULL
Rocky-------------------NULL-----------------NULL---------------------- 9
Appreciate any help
* ---- are used for identation purpose only
Thank You 🙂
What you have there is actually a Pivot or, in old terms, a Cross Tab. Here's a couple of articles that explain (step by step in simple terms) how to hardcode one and how to do it dynamically on the other.
http://www.sqlservercentral.com/articles/T-SQL/63681/
http://www.sqlservercentral.com/articles/Crosstab/65048/
--Jeff Moden
Change is inevitable... Change for the better is not.
May 1, 2013 at 10:23 pm
Ah... sorry. Might not be right for you. Didn't see where you doubled up on "Rocky". the dynamic SQL article I previously mentioned might help, though.
--Jeff Moden
Change is inevitable... Change for the better is not.
May 2, 2013 at 2:02 am
Hi All,
Thanks for the help.
Got it 🙂
Below is the query:
select * from
(select customer
,sum(qty) qty1
,(select cast(product as varchar(max)) from datatable where customer = a1.customer for XML path(''))product
from datatable a1
group by customer
)dataforpivot_table
pivot (sum(qty1) for product in ([Mango],[Orange],[MangoOrange]))pivoted;
Products are not fixed, they keep on changing, and even the combinations change.
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply