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
 Aggregating with Pivot - SQL Server 2000

Author  Topic 

mayoorsubbu
Yak Posting Veteran

95 Posts

Posted - 2014-01-24 : 22:30:18
Hi All,

I have three table in sql server 2000 like so

tbDemand
DemandNo varchar
Unit varchar

tbDemandItems
DemandNo varchar
Itemcode int
DemandQty

Data in tables

tbDemand
DemandNo Unit
2014ABC RST
2014CDF XYZ

tbDemandItems
DemandNo Itemcode DemandQty
2014ABC 1234 5
2014ABC 4567 10
2014ABC 7890 11
2014CDF 1234 10
2014CDF 7890 5

I want a report as follows

Itemcode RST XYZ TotDemandQty
1234 5 10 15
4567 10 0 10
7890 11 5 16

The pivot on unit has to be dynamic as per no of units, which is variable and not fixed in tbDemand table.

Thanks.

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-01-27 : 06:54:28
[code]
SELECT di1.Itemcode,
SUM(CASE WHEN Unit='RST' THEN DemandQty ELSE 0 END) AS RST,
SUM(CASE WHEN Unit='XYZ' THEN DemandQty ELSE 0 END) AS XYZ,
SUM(DemandQty) AS TptDemandQty
FROM tbDemand d
CROSS JOIN (SELECT DISTINCT Itemcode FROM tbDemandItems) di1
LEFT JOIN tbDemadnItems di
ON di.DemandNo = d.DemandNo
AND di.Itemcode = di1.Itemcode
GROUP BY di1.Itemcode
[/code]

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

mayoorsubbu
Yak Posting Veteran

95 Posts

Posted - 2014-01-27 : 09:45:04
Visakh,

Thank u for the reply, but the case statement cannot be hard coded as the unit names will vary

(CASE WHEN Unit='RST' THEN DemandQty ELSE 0 END)
unit will vary and cannot be predicted before hand. The unit will have be selected from the tbDemand table and then the case statement constructed. Hope I am clear.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-01-27 : 13:59:17
ok..then extend it as per below to get unit value at runtime

http://sqlblogcasts.com/blogs/madhivanan/archive/2007/08/27/dynamic-crosstab-with-multiple-pivot-columns.aspx

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

mayoorsubbu
Yak Posting Veteran

95 Posts

Posted - 2014-01-27 : 19:37:57
Thanks will comply
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2014-01-28 : 03:03:10
welcome

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

- Advertisement -