Avatar of Rivess
RivessFlag for Australia

asked on 

How to get one record from a range in an sql view based on the value of a field in another table

Hi there:

I have an Employees table with the fields called EmployeeName and YearsOfService. I have another table called Bonus that contains the fields: MinimumYears and BonusAmt. I want to create a view that displays the EmployeeName, YearsOfService and BonusAmt (one record per employee).

The Bonus table has the values:
MinimumYears | Bonus
0 | 0
2 | 1000
4 | 2800
6 | 4000

Two records in the Employees table may read:
EmployeeName | YearsOfService
Barry Blue | 2.65
Wayne Brown | 4.80
Greg White |1.94

The final view should read:
EmployeeName | YearsOfService | BonusAmt
Barry Blue | 2.65 | 1000
Wayne Brown | 4.80 | 2800
Greg White |1.94 | 0

So, what would be the SQL statement to get the required results?
Microsoft SQL Server 2008Microsoft SQL Server 2005

Avatar of undefined
Last Comment
Rivess
ASKER CERTIFIED SOLUTION
Avatar of sameer2010
sameer2010
Flag of India image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
You could use below one as well.

create view bonusview as 

select
e.EmployeeName,e.YearsOfService, b.bonus
from
Employees_Table e
inner join  Bonus_Table  b on b.MinimumYears =  Floor(e.YearsOfService)

Open in new window

Avatar of Rivess
Rivess
Flag of Australia image

ASKER

A simple and tricky piece of code.
Avatar of Rivess
Rivess
Flag of Australia image

ASKER

The second solution requires an entry for each possible year in the Bonus table. In the current setup an employee with 3 years won't get any bonus at all since the 'Floor(X)' is trying to match a 3 in the bonus table and an entry with 3 years does not exist. Thanks for your prompt reply.
Microsoft SQL Server 2005
Microsoft SQL Server 2005

Microsoft SQL Server 2005 is a suite of relational database management system (RDBMS) products providing multi-user database access functionality.Component services include integration (SSIS), reporting (SSRS), analysis (SSAS), data quality, master data, T-SQL and performance tuning. It includes support for managing XML data and allows a database server to be exposed over web services using Tabular Data Stream (TDS) packets encapsulated within SOAP (protocol) requests.

72K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo