Click here to Skip to main content
15,890,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi !

I am working on SQL Server 2008 Database.

I show you a table with data and then i show you what a result i want then suggest me the best solution.

Table Name tbl_Inventory
following shows the data in table.

Tansaction	ItemName	Quantity	Status
In on 1/1/2015	Square Pipe	15	Ordered
In on 1/1/2015	Square Pipe	10	Ordered
In on 1/1/2015	Square Pipe	20	Ordered
In on 1/1/2015	Square Pipe	5	Loaded
In on 1/1/2015	Square Pipe	12	Loaded
In on 1/1/2015	Square Pipe	8	Loaded
In on 1/1/2015	Square Pipe	16	Shipped
In on 1/1/2015	Square Pipe	20	Shipped
In on 1/1/2015	Square Pipe	7	Shipped
In on 1/1/2015	Square Pipe	25	Billed
In on 1/1/2015	Square Pipe	9	Billed
In on 1/1/2015	Square Pipe	11	Billed
In on 1/1/2015	Round Pipe	40	Ordered
In on 1/1/2015	Round Pipe	10	Loaded
In on 1/1/2015	Round Pipe	24	Loaded
In on 1/1/2015	Round Pipe	16	Loaded
In on 1/1/2015	Round Pipe	32	Shipped
In on 1/1/2015	Round Pipe	40	Shipped
In on 1/1/2015	Round Pipe	14	Shipped
In on 1/1/2015	Round Pipe	50	Billed
In on 1/1/2015	Round Pipe	18	Billed
In on 1/1/2015	Round Pipe	22	Billed



Now i want the following result
ItemName      OrderedQty   LoadedQuantity   ShippedQuantity   BilledQuantity
SquarePipe        45             25               43              45  
RoundPipe         90             50               86              90


i hope you will understand although there is some problem in table format but i think the basic concept is clear what i want.

please help me

thanks
Posted
Updated 22-Aug-15 5:35am
v2

One way to do this is...

SQL
SELECT ItemName
, SUM(CASE [Status] WHEN 'Ordered' THEN Quantity ELSE 0 END) as OrderedQty 
, SUM(CASE [Status] WHEN 'Loaded' THEN Quantity ELSE 0 END) as LoadedQuantity 
, SUM(CASE [Status] WHEN 'Shipped' THEN Quantity ELSE 0 END) as ShippedQuantity 
, SUM(CASE [Status] WHEN 'Billed' THEN Quantity ELSE 0 END) as  BilledQuantity
FROM tbl_Inventory
GROUP BY ItemName
 
Share this answer
 
What you're after is called a PIVOT. The query could look something like:
SQL
select *
from (select itemname, quantity, status from tablename) a
pivot (
   sum(quantity)
   for status in (['Ordered'], ['Loaded'],['Shipped'],['Billed']) 
) as amount

For more information, see https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx[^]
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900