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
 should I use PIVOT?

Author  Topic 

JohnDW
Starting Member

45 Posts

Posted - 2014-02-22 : 16:42:02
I have the following query

select product.Name, product.SizeId, orderdetail.Tal as Total 
from Product inner join Orderdetail on product.ProductId = orderdetail.ProductId
inner join Orders on orderdetail.OrderId = orders.orderid where
Orders.Orderdate BETWEEN '20130701' AND '20131231' and product.CategorieId like '%adventure'


that gives as result:
vgv 80 A 1
vgv 85 B 1
vgv 80 A 1

tail 75 C 1
tail 85 B 1
tail 85 B 1


the result I want =

product.sizeid 75 C 80 A 85 B

product.Name vgv 0 2 1
product.Name tail 1 0 2

Sort of cross table query.

I'll tried Pivot in sql server:


How do I make this work?
I tried:

select product.Name, product.SizeId as maat from
(select product.Name, product.SizeId, orderdetail.Tal as Aantal
from product inner join Orderdetail on product.ProductId = orderdetail.ProductId
inner join Orders on orderdetail.OrderId = orders.orderid where
Orders.Orderdatum BETWEEN '20130701' AND '20131231' and product.CategorieId like '%aventure' )
pivot
(sum(orderdetail.tal) for SizeId in SizeId) as pivoting


But this doesn't work.

if you do not try, it will not work

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-02-23 : 03:04:04
[code]
select select Name,
COALESCE([80 A],0) AS [80 A],
COALESCE([75 C],0) AS [75 C],
COALESCE([85 B],0) AS [85 B]
from
(select product.Name, product.SizeId, orderdetail.Tal as Aantal
from product inner join Orderdetail on product.ProductId = orderdetail.ProductId
inner join Orders on orderdetail.OrderId = orders.orderid where
Orders.Orderdatum BETWEEN '20130701' AND '20131231' and product.CategorieId like '%aventure' )t
pivot
(sum(tal) for SizeId in ([80 A],[75 C],[85 B])) as pivoting
[/code]

for making it dynamic see
http://beyondrelational.com/modules/2/blogs/70/posts/10840/dynamic-pivot-in-sql-server-2005.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

JohnDW
Starting Member

45 Posts

Posted - 2014-02-25 : 15:22:28
Txs a lot!

I'll study it further!

Grtz.
J

if you do not try, it will not work
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-02-27 : 02:49:17
cool

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -