Solved

# COnvert rows to columns

Posted on 2011-10-18
Medium Priority
363 Views
I have a table OrderLine

OrderNumber
OrderDate
OrderItemCode
OrderQty

I have another table OrderItem
with a single column OrderItemCode

The table OrderItem has five rows with OrderItemCode's A, B, C, D, E. This is a constant number of rows.

The table OrderLine has eight rows

o1 , 10/14/2011,  A , 10
o1 , 10/14/2011,  B , 12
o2 , 10/14/2011,  A , 6
o2 , 10/15/2011,  C , 5
o3 , 10/14,2011,  D , 11
o3 , 10/16/2011,  E , 9
o3 , 10/16/2011,  D , 5
o3 , 10/17/2011,  B , 11

I want to convert this to a table, with these seven columns

OrderNumber, OrderDate, A, B, C, D, E

And the final output should be as follows, since I wnt to group by OrderNumber and OrderDate

o1 , 10/14/2011, 10 , 12 , , , ,

o2 , 10/14/2011, 6  ,    , , , ,
o2 , 10/15/2011,    ,    , 5 , , ,
o3 , 10/14/2011,   ,    , ,11 , ,

o3 , 10/16/2011,   ,    , ,5 ,9 ,

o3 , 10/17/2011,   , 11   , , , ,
0
Question by:countrymeister
• 2

LVL 9

Accepted Solution

sachinpatil10d earned 2000 total points
ID: 36990510
Try this
``````select * from
(select * from OrderLine )
p
pivot
(sum(orderQty) for
orderitemcode in ([A],[B],[C],[D],[E])
) as pvt
``````
0

LVL 9

Expert Comment

ID: 36990517
order by ordernumber added in the below query for exact output

``````select * from
(select * from OrderLine )
p
pivot
(sum(orderQty) for
orderitemcode in ([A],[B],[C],[D],[E])
) as pvt
order by ordernumber
``````
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
With just a little bit of  SQL and VBA, many doors open to cool things like synchronize a list box to display data relevant to other information on a form.  If you have never written code or looked at an SQL statement before, no problem! ...  give i…
###### Suggested Courses
Course of the Month13 days, 22 hours left to enroll