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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 PIVOT with 2 measures

Author  Topic 

KlausEngel
Yak Posting Veteran

85 Posts

Posted - 2011-08-24 : 10:39:51
I would like my query to PIVOT over 2 measures.
My quer looks as follows:

SELECT * FROM
(SELECT
a.ArticleNumber
, a.ArticleDescription
, c.CountryName
, s.sales_quantity
, s.sales_amount
FROM Articles a
LEFT JOIN SalesSummary s on a.ArticleNumber = s.ArticleNumber
INNER JOIN Countries c on s.CountryCode = c.CountryCode) Data
PIVOT
(
SUM(sales_quantity)
FOR CountryName
IN (
[USA] ,[CANADA] , [MEXICO] ,[BRAZIL] ,[ARGENTINA]
)
) PivotTable


This works as it should, giving me a breakdown of my sold quantities per country, but now I also would like to add the sales amount value to the result set.
Any direction how to add the SUM(sales_amount)?
Thanks.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2011-08-24 : 12:10:47
for multiple pivot you need to use like

SELECT
a.ArticleNumber
, a.ArticleDescription
,SUM(CASE WHEN c.CountryName = 'USA' THEN sales_quantity ELSE 0 END) AS [USAQty]
,SUM(CASE WHEN c.CountryName = 'CANADA' THEN sales_quantity ELSE 0 END) AS [CANADAQty]
,SUM(CASE WHEN c.CountryName = 'MEXICO' THEN sales_quantity ELSE 0 END) AS [MEXICOQty]
,SUM(CASE WHEN c.CountryName = 'BRAZIL' THEN sales_quantity ELSE 0 END) AS [BRAZILQty]
,SUM(CASE WHEN c.CountryName = 'ARGENTINA' THEN sales_quantity ELSE 0 END) AS [ARGENTINAQty]
,SUM(CASE WHEN c.CountryName = 'USA' THEN sales_amount ELSE 0 END) AS [USAAmt]
,SUM(CASE WHEN c.CountryName = 'CANADA' THEN sales_amount ELSE 0 END) AS [CANADAAmt]
,SUM(CASE WHEN c.CountryName = 'MEXICO' THEN sales_amount ELSE 0 END) AS [MEXICOAmt]
,SUM(CASE WHEN c.CountryName = 'BRAZIL' THEN sales_amount ELSE 0 END) AS [BRAZILAmt]
,SUM(CASE WHEN c.CountryName = 'ARGENTINA' THEN sales_amount ELSE 0 END) AS [ARGENTINAAmt]
FROM Articles a
LEFT JOIN SalesSummary s on a.ArticleNumber = s.ArticleNumber
INNER JOIN Countries c on s.CountryCode = c.CountryCode
GROUP BY a.ArticleNumber
, a.ArticleDescription


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

Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2011-08-29 : 07:29:05
You may also refer
http://beyondrelational.com/blogs/madhivanan/archive/2007/08/27/dynamic-crosstab-with-multiple-pivot-columns.aspx

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -