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)
 Help with SQL query

Author  Topic 

pan
Starting Member

2 Posts

Posted - 2009-08-13 : 14:37:10
I was not sure what tittle to give to please forgive me for that. I am new to SQL server and need help.
I have a query

SELECT dbo.Employee.EmployeeHREmpNum,
dbo.Employee.EmployeeLName,
MIN(dbo.JobTitle.JobTitleString) AS JobTitle1,
MAX(dbo.JobTitle.JobTitleString) AS JobTitle2,
COUNT(dbo.JobTitle.JobTitleString) AS JobTitleCnt
FROM dbo.Employee INNER JOIN
dbo.JctJobTitle ON dbo.Employee.EmployeeID = dbo.JctJobTitle.EmployeeID INNER JOIN
dbo.JobTitle ON dbo.JctJobTitle.JobTitleID = dbo.JobTitle.JobTitleID
GROUP BY dbo.Employee.EmployeeHREmpNum,
dbo.Employee.EmployeeLName

the output of which is

Emp# Ename Tittle1 Tittle2 Count
800366489 GALON CHEF SOUS COOK 2

I want to re-write so that a 3rd tittle can be displayed. Please help

Thanks in advance

vijayisonly
Master Smack Fu Yak Hacker

1836 Posts

Posted - 2009-08-13 : 15:06:25
from which table is this new title coming from?...add that table in the JOIN and include the fieldname in the select list.
Go to Top of Page

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2009-08-13 : 15:17:05
Here's one way. It will allow for you to add as many title columns as you want:

SELECT e.EmployeeHREmpNum
,e.EmployeeLName

,max(case when ca.rn = 1 then ca.JobTitleString end) as JobTitle1
,max(case when ca.rn = 2 then ca.JobTitleString end) as JobTitle2
,max(case when ca.rn = 3 then ca.JobTitleString end) as JobTitle3
,max(ca.rn) AS JobTitleCnt

FROM dbo.Employee e
cross apply (
select jt.JobTitleString
,row_number() over (order by jt.jobTitleString) rn
from dbo.JctJobTitle jjt
inner join dbo.JobTitle jt
ON jt.JobTitleID = jjt.JobTitleID
where jjt.EmployeeID = e.employeeid
) ca
GROUP BY e.EmployeeHREmpNum
,e.EmployeeLName


Be One with the Optimizer
TG
Go to Top of Page

pan
Starting Member

2 Posts

Posted - 2009-08-13 : 17:18:51
TG, thanks it worked like charm. I appreciate your help.
Go to Top of Page
   

- Advertisement -