Solved

SQL calculate years from view

Posted on 2011-03-24
276 Views
I have a view that has a
EmployeeNumber, companyname, startdate, and enddate

I need to find a way to calculate years of experience for each employeenumber when they worked at the company MYCOMPANY, and also a total of all years worked at another company.

I don't care it this ends up being two rows in the same view for each employeenumber (only one if they don't have other experience), or two different views.

SELECT     EmpNo, CompanyName, Location, Title, StartDate, EndDate
FROM         dbo.EmpWorkHistory AS e
GROUP BY EmpNo, StartDate, EndDate, CompanyName, Location, Title
ORDER BY EmpNo, StartDate

so
1, IBM, 1991-1-1, 1992-1-1
1, XXX, 1992-1-1, 1993-1-1
1, MyCompany, 1993-1-1, 1994-1-1

would give me
1, MyCompany, 1 Year
1, AllOtherCompanies, 3 Years

Thanks!
0
Question by:jackjohnson44
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 2

LVL 28

Accepted Solution

Ryan McCauley earned 500 total points
ID: 35211038
Is this what you want?

``````SELECT CASE Company WHEN 'MyCompany' THEN 'MyCompany' ELSE 'AllOtherCompanies' END as Company,
SUM(DATEDIFF(yy, StartDate, EndDate)) as YearsExperience
FROM dbo.EmpWorkHistory AS e
GROUP BY CASE Company WHEN 'MyCompany' THEN 'MyCompany' ELSE 'AllOtherCompanies' END
``````
0

LVL 28

Assisted Solution

Ryan McCauley earned 500 total points
ID: 35211069
Wow - I don't know what I was thinking - that's not at all what you want. Here's what you're looking for, and can do it in a single row per employee:

``````SELECT EmpNo, SUM(CASE Company WHEN 'MyCompany' THEN DATEDIFF(yy, StartDate, EndDate) ELSE 0 END) as YearsWithUs,
SUM(CASE Company WHEN 'MyCompany' THEN 0 ELSE DATEDIFF(yy, StartDate, EndDate) END) as YearsSomewhereElse
FROM dbo.EmpWorkHistory AS e
GROUP BY EmpNo
``````
0

Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
It is possible to export the data of a SQL Table in SSMS and generate INSERT statements. It's neatly tucked away in the generate scripts option of a database.
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.
Suggested Courses
Course of the Month5 days, 18 hours left to enroll