June 18, 2013 at 10:33 am
Hello,
I need to create a pivot table, and I think I need a new column to get the pivot to work. Basically, what I have is data with customer#, customername and dist. Each customer can have more than 1 distributor, and I want my data to be arranged like: customer#, customername, dist1, dist2, dist3, etc (as many as they have).
I think I need to add a number column that will count each dist for each customer. But how do I do this?
Thanks!
Mary
June 18, 2013 at 10:39 am
if you know there is a maximum number of distributores, it's pretty easy; for example, this would assume a max of five distributora records:
WITH CTE AS (
SELECT customer#, customername,
ROW_NUMBER() OVER(PARTITION BY customer# ORDER BY dist) AS rn
FROM MyTable)
SELECT customer#,
MAX(CASE WHEN rn=1 THEN dist END) AS dist1,
MAX(CASE WHEN rn=2 THEN dist END) AS dist2,
MAX(CASE WHEN rn=3 THEN dist END) AS dist3,
MAX(CASE WHEN rn=4 THEN dist END) AS dist4,
MAX(CASE WHEN rn=5 THEN dist END) AS dist5
FROM CTE
GROUP BY customer#
Lowell
June 18, 2013 at 3:13 pm
Thank you. Luckily for me it turns out the highest # of distributors used is 17, so I can work with this.
Thanks for your help!!
Mary
June 18, 2013 at 4:15 pm
Thanks!
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply