Can you please help in below sql server query

I have data like below in a sql server table

NY    Albany
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

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

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

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 ;)
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
PortletPaulEE Topic AdvisorCommented:
>>"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.
The 7 Worst Nightmares of a Sysadmin

Fear not! To defend your business’ IT systems we’re going to shine a light on the seven most sinister terrors that haunt sysadmins. That way you can be sure there’s nothing in your stack waiting to go bump in the night.

vijay11Author Commented:
i am getting results like

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

select ny,nj,ct
from (select state,city from table)
max(state) in [ny,nj,ct)
PortletPaulEE Topic AdvisorCommented:
{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:
     rn, [NJ], [NY], [CT]
    select [city],[state], row_number() over(partition by State order by City ASC) as rn
    from table1
    ) p
      FOR [state] IN ( [NJ], [NY], [CT] )
      ) AS pvt

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.
vijay11Author Commented:
i have to present this information in excel to user
vijay11Author Commented:
Thanks. if I have many states . Can we do this dynamically?
PortletPaulEE Topic AdvisorCommented:
I changed my previous comment, sorry, you may have read it before the edit was made.
PortletPaulEE Topic AdvisorCommented:
Yes it can be dynamic.
vijay11Author Commented:
if possible can you please help with dynamic sql also and thanks a lot
PortletPaulEE Topic AdvisorCommented:

            FROM table1 s
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')

SET @query = 'SELECT rn, ' + @cols + ' FROM
                    , [city]
                    , row_number() over(partition by [State] order by [City] ASC) as rn
                 FROM table1
           ) sourcedata
                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:!6/505ee/1

nb: I re-used code I provided at this question:

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.
vijay11Author Commented:
Thanks  a lot. Perfect solution.
PortletPaulEE Topic AdvisorCommented:
Thank you.
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.