Can you please help in below sql server query

Hello,
I have data like below in a sql server table

NY    Albany
NY   NYC
NY   Rochester
NY  Buffalo
Nj    Princeton
Nj Trenton
Ct  Milford
Ct  Hartford
Ct  Stanford

I want output as below

Ny                    Nj                         ct
Albany           princeton        milford
NYC                Trenton           hartford
Rochester                               stanford
Buffalo

Can any one please help . I want a dynamic script for this. there can be n' number of states

Thanks
vijay11Asked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ste5anSenior DeveloperCommented:
See Dynamic Pivot Procedure for SQL Server.

But having n elements does not necessarily means you need dynamic SQL. In your case n is limited and countable. When I need to guess it's about 50 or so ;)
0
vijay11Author Commented:
Hello I tried with above example but I could not get what I wanted. I have many states from different countries. Can some one please give the SQL if possible
0
PortletPaulfreelancerCommented:
>>"I tried with above example but I could not get what I wanted"

Post that attempt and any errors it produced and we can help you. This way you learn.
0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

vijay11Author Commented:
i am getting results like

Ny   Nj Ct
Ny  Nj   Ct
Ny  Nj  Ct
.
.
It is repeated 9 times
0
PortletPaulfreelancerCommented:
post your query please
0
vijay11Author Commented:
I work in a financial client . sites don't open in office. I am typing this from home. Sorry
0
vijay11Author Commented:
May be some thing like this.

select ny,nj,ct
from (select state,city from table)
pivot
max(state) in [ny,nj,ct)
0
PortletPaulfreelancerCommented:
{this comment has been edited}

How are you presenting this information? e.g. in HTML
You may find it easier to achieve using that FINAL "presentation layer" instead of SQL

This pivot query may assist:
SELECT 
     rn, [NJ], [NY], [CT]
FROM (
    select [city],[state], row_number() over(partition by State order by City ASC) as rn
    from table1
    ) p
PIVOT (
      max(city)
      FOR [state] IN ( [NJ], [NY], [CT] )
      ) AS pvt
ORDER BY rn

Open in new window

the result looks like this:
| rn |        NJ |        NY |       CT |
|----|-----------|-----------|----------|
|  1 | Princeton |    Albany | Hartford |
|  2 |   Trenton |   Buffalo |  Milford |
|  3 |    (null) |       NYC | Stanford |
|  4 |    (null) | Rochester |   (null) |

Open in new window


Note I am using ROW_NUMBER() to generate something that you can "pivot around". You can suppress output of that column if needed.
0
vijay11Author Commented:
i have to present this information in excel to user
0
vijay11Author Commented:
Thanks. if I have many states . Can we do this dynamically?
0
PortletPaulfreelancerCommented:
I changed my previous comment, sorry, you may have read it before the edit was made.
0
PortletPaulfreelancerCommented:
Yes it can be dynamic.
0
vijay11Author Commented:
if possible can you please help with dynamic sql also and thanks a lot
0
PortletPaulfreelancerCommented:
DECLARE @cols AS NVARCHAR(MAX)
DECLARE @query  AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT DISTINCT ',' + QUOTENAME(s.state)
            FROM table1 s
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

SET @query = 'SELECT rn, ' + @cols + ' FROM
            (
                SELECT
                      [state]
                    , [city]
                    , row_number() over(partition by [State] order by [City] ASC) as rn
                 FROM table1
           ) sourcedata
            pivot
            (
                 max([city])
                FOR [state] IN (' + @cols + ')
            ) p '

--select @query -- use select to inspect the generated sql
execute(@query) -- once satisfied that sql is OK, use execute
;

Open in new window


see it working here: http://sqlfiddle.com/#!6/505ee/1

nb: I re-used code I provided at this question:
http://www.experts-exchange.com/questions/28188971/Need-some-help-using-pivot-in-a-query-SQL-2008-R2.html
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ste5anSenior DeveloperCommented:
When you do in Excel, then it is a front-end task. Excel is much better in pivoting data than SQL Server.
0
vijay11Author Commented:
Thanks  a lot. Perfect solution.
0
PortletPaulfreelancerCommented:
Thank you.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.