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 2005 Forums
 Transact-SQL (2005)
 My "50 First Dates" with a pivot table tsql query

Author  Topic 

janwane
Starting Member

9 Posts

Posted - 2010-04-08 : 12:40:26
I have an SQLserver normallized db and have a requirement that could possibly be handled by a single tsql pivot table query which I'll put in an SqlDataSource in VS2008. I got syntax & samples but sample uses a simplified single unnormalized table as the source. When I try to implement my multiple-join query, I don't get anywhere. My query is:

SELECT Users.NameLast, ContractMaster.ContractName + ' ' + ClinMaster.ClinName AS ContractClin,
ClinItemEmpXref.EmpShare
FROM EmpClinShare INNER JOIN ClinItemEmpXref ON EmpClinShare.CDUID = ClinItemEmpXref.CDUID
INNER JOIN CLINdetail ON ClinItemEmpXref.ItemID = CLINdetail.ItemID
INNER JOIN ClinMaster ON CLINdetail.ClinID = ClinMaster.ClinID
INNER JOIN ContractMaster ON ClinMaster.ContractID = ContractMaster.ContractID
RIGHT OUTER JOIN Users ON ClinItemEmpXref.UserID = Users.UserID
WHERE (EmpClinShare.ProjMo = '2/1/2010')
ORDER BY Users.NameLast, ContractClin

giving this result (sample):

NameLast Contract Share
Barber 4.2.5 0.5
Brotherton 4.2.1.2 1
Caddell C130 0.8
Caira NDAC 0.2
Caira PTA 0.4
Caira TEFBS 0.1

This is how I tried to turn my join query into a pivot table query:

SELECT Users.NameLast
FROM EmpClinShare INNER JOIN ClinItemEmpXref ON EmpClinShare.CDUID = ClinItemEmpXref.CDUID
INNER JOIN CLINdetail ON ClinItemEmpXref.ItemID = CLINdetail.ItemID
INNER JOIN ClinMaster ON CLINdetail.ClinID = ClinMaster.ClinID
INNER JOIN ContractMaster ON ClinMaster.ContractID = ContractMaster.ContractID
RIGHT OUTER JOIN Users ON ClinItemEmpXref.UserID = Users.UserID
PIVOT
(
SUM(EmpClinShare.EmpShare)
FOR Users.NameLast IN ([ClinMaster.ClinName])
)
AS p

but it errors out. This is what I want:

NameLast 4.2.5 4.2.1.2 C130 NDAC PTA TEFBS
Barber 0.5
Brotherton 1
Caddell 0.8
Caira 0.2 0.4 0.1


Can anyone help me turn my join query into a pivot table query? Thank you!

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-04-08 : 12:45:11
see

http://beyondrelational.com/blogs/madhivanan/archive/2008/08/27/dynamic-pivot-in-sql-server-2005.aspx

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

Go to Top of Page
   

- Advertisement -