Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 How to display rows as columns

Author  Topic 

angelinacunningham
Starting Member

2 Posts

Posted - 2011-07-29 : 18:33:47
Hi to all, I'm a new member in this forum..

Is it possible to return the rows as column?

I have a table History with 4 columns

ITEMS | ACTUAL INVENTORY | DATE | CONSUMED
CUPS 14 07/21/2011 2
CUPS 14 07/22/2011 4
CUPS 14 07/23/2011 0
MILK 11 07/21/2011 4
MILK 11 07/22/2011 10
MILK 11 07/23/2011 5
COFFEE 6 07/21/2011 1
COFFEE 6 07/22/2011 3
COFFEE 6 07/23/2011 0

I want to display my table like this:

ITEMS | ACTUAL INVENTORY | 07/21/2011 | 07/22/2011 | 7/23/2011 |
CUPS 14 2 4 0
MILK 11 4 10 5
COFFEE 6 1 3 0

I like to display the row of dates on the column because it is very clean.

Is this possible?

Can anyone explain to me how to do this?


Thanks......

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2011-07-29 : 21:10:53
If the three dates are known in advance and if you are on SQL 2005 or higher, you can use the PIVOT construct - see here. There is description and a few examples there.

If you don't know the dates in advance, you will need to use dynamic pivot. Madhivanan's blog has a function and sample code. Copy the function and install it on your server, and then use it just like he demonstrates in his examples.

If you hit a wall, post back with your code and people on this forum would be able to help you fix it.
Go to Top of Page

angelinacunningham
Starting Member

2 Posts

Posted - 2011-07-29 : 21:57:02
thanks for the reply. I will definitely try this... I will let you know if I have problems..
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-07-30 : 01:48:14
If your front end is by any chance reporting tool like SQL Reporting services, you can very easily get this output by using dynamic column grouping.

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -