What you are asking for is called a cross-tab report or pivot. Its purpose
is to present data for display or printing and there are good reasons why it
makes sense to do this in your client application or reporting tool rather
than SQL. SQL Server is designed and optimised for the data tier of an
N-tier architecture. Presentational functions belong elsewhere.
One problem with your requirement is that the number, name and datatype of
columns in a query is usually static. In order to change the columns
returned at runtime you will probably have to use Dynamic SQL. Most of the
time you should try to avoid putting dynamic SQL in your application because
doing so has certain performance, security and other implications that make
dynamic code undesirable in many cases.
Here are some references on how to produce cross-tab reports:
http://www.aspfaq.com/show.asp?id=2462
Here's a an article on dynamic SQL that explains some of the problems and
the correct and incorrect uses of dynamic code:
http://www.sommarskog.se/dynamic_sql.html
--
David Portas
SQL Server MVP
--