473,811 Members | 2,714 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Having trouble getting an inline SQL Query to compare

9 New Member
I've got to fix a system that was basically handed to me. As it currently functions we have four tables as such:

1) Project Hours (includes EmployeeID, ProjectID, Date, Hours)
2) Payrates (includes EmployeeID, Payrate) <-- NOT VISIBLE TO EMPLOYEES
3) EmployeeIDs (includes ID, First, Last, ExpenseCategory )
4) ExpenseCodes (includes ExpenseCategory , ExpenseCode)

Our queries are setup such that they can calculate how much we've spent on a project by joining all the tables and calculating Hours*Payrate.

Problem: Anytime someone gets a new pay, they need a new ID, and some way to tell, on the form where they enter hours, what name to put on which days worked. (Sometimes employees will wait until the end of the 2-week pay period, or longer, to enter their hours to a specific project.) This is rather cumbersome and annoying.

I've setup a table to keep track of different pay rates per person with the following attributes:

PayRateCodes:
UID - unique ID
EmployeeID
Rate - a dollar amount
BeginDate
EndDate

When we run the query to generate the table which summarizes the cost of the project out of the Project Hours table, I'd like it to look-up, for each record, the appropriate Rate in the PayRateCodes table by comparing the ProjectHours.Da te to PayRateCodes.Be ginDate and PayRateCodes.En dDate. (Complication, to make things easy on the accounting person, I've allowed EndDate to be blank. If it is so, I'd like the Date to be considered less than it.)

Pseudo-SQL Code:

SELECT ProjectHours.Em ployeeID, ProjectHours.Pr ojectID, ProjectHours.Da te, ProjectHours.Ho urs, (SELECT PayRateCodes.Ra te WHERE PayRateCodes.Em ployeeID = ProjectHours.Em ployeeID AND PayRateCodes.Be ginDate < ProjectHours.Da te < ProjectHours.En dDate) as Rate1, Rate1*Hours as CostExpr FROM [Massive Inner Join Here based on table relationships] WHERE ProjectHours.Pr ojectID = "12".

I know that doesn't work. I'm hoping it explains what I want to do. If this can be done just within a query, that would be preferable, since adding a form to the mix might scare everyone here.
Jan 11 '07 #1
13 3613
NeoPa
32,579 Recognized Expert Moderator MVP
2) Payrates (includes EmployeeID, Payrate) <-- NOT VISIBLE TO EMPLOYEES
Is this relevant to the question at all?
(Complication, to make things easy on the accounting person, I've allowed EndDate to be blank. If it is so, I'd like the Date to be considered less than it.)
I don't understand what you're trying to say here. Less than what? Null?
Ah, maybe I've sussed it - do you mean 'Date()' rather than 'the Date'?

I'll try to look at this and see what I can come up with later.
Jan 12 '07 #2
NeoPa
32,579 Recognized Expert Moderator MVP
Angwe,
As you have access to your database, try creating the query you're thinking of in the design view window of a new query.
When you have it as close as possible to how you want it then post the SQL here (View / View SQL) along with the Querydef name. Then we don't have to do so much work on the simple stuff that Access can do very well for you.
BTW I wouldn't use a subquery here at this stage unless absolutely necessary. It seems it can more easiley done with a simple join.
Jan 12 '07 #3
angwe23
9 New Member
Angwe,
As you have access to your database, try creating the query you're thinking of in the design view window of a new query.
When you have it as close as possible to how you want it then post the SQL here (View / View SQL) along with the Querydef name. Then we don't have to do so much work on the simple stuff that Access can do very well for you.
BTW I wouldn't use a subquery here at this stage unless absolutely necessary. It seems it can more easiley done with a simple join.
A join would be the way to go, but the column "Date" in the table "ProjectHou rs" is a single date. The join would have to be based on that date being either:

1) within the range of BeginDate to EndDate in the PayRateCodes table (PayRateCodes.B eginDate < ProjectHours.Da te < PayRateCodes.En dDate)

OR

2) at least greater than the BeginDate if the EndDate is blank. (PayRateCodes.B eginDate < ProjectHours.Da te AND PayRateCodes.En dDate isBlank)

I want a join based on a comparison, not on any direct relationship between the Project Hours table and the PayRateCodes table, and I'm not sure how to do that with Access.
Jan 22 '07 #4
angwe23
9 New Member
Here's how far I've been able to get it to work.

TestQuery1 builds a new table TestTable by executing the following SQL:
Expand|Select|Wrap|Line Numbers
  1. SELECT [Project Hours].Project, EmployeeIDs1.[Expense Category], EmployeeIDs1.FirstName, [Project Hours].Date, [Project Hours].Hours, EmployeeIDs1.ID INTO TestTable
  2. FROM (EmployeeIDs1 INNER JOIN [Expense Codes1] ON EmployeeIDs1.[Expense Category] = [Expense Codes1].[Expense Category]) INNER JOIN [Project Hours] ON EmployeeIDs1.ID = [Project Hours].[Employee ID]
  3. WHERE ((([Project Hours].Project)="61"));
  4.  
That gives me a table with all the relevant info for any particular project from out of the Project Hours table.

As a second step, I want to go through each of these records and build a table that adds the appropriate pay rate as a column (and then, eventually, multiplies the hours by the payrate, but I can figure out how to do that, once I can get the payrate correct).

Here is TestQuery2:

Expand|Select|Wrap|Line Numbers
  1. SELECT TestTable.*, PayRateCodes.Rate
  2. FROM TestTable INNER JOIN PayRateCodes ON TestTable.ID = PayRateCodes.EmployeeID
  3. WHERE (((([PayRateCodes].[BeginDate]<[TestTable].[Date]<[PayRateCodes].[EndDate]) Or (([TestTable].[Date]>[PayRateCodes].[BeginDate]) And ([PayRateCodes].[EndDate]="")))));
  4.  
However, I have run this for one particular project that spans a payrate for the testing employee but it only assigns the first payrate, it does not assign the proper payrate for the dates after the pay rate change.

It seems like I can't make the JOIN conditional.

Hope this clears things up.

-R
Jan 22 '07 #5
angwe23
9 New Member
New version of the second query. I didn't realize that access will futz with the SQL you've written if you aren't careful.

Expand|Select|Wrap|Line Numbers
  1. SELECT TestTable.*, PayRateCodes.Rate
  2. FROM TestTable INNER JOIN PayRateCodes ON ((TestTable.ID=PayRateCodes.EmployeeID) AND ((PayRateCodes.BeginDate<TestTable.Date<PayRateCodes.EndDate) OR ((TestTable.Date>PayRateCodes.BeginDate) And (PayRateCodes.EndDate=""))));
  3.  
It still doesn't work, but now I think the Join is properly formatted.
Jan 22 '07 #6
angwe23
9 New Member
Attempting to follow MS's suggestions for conditional Joining (which I finally found in the damn help) I now have the following:

Expand|Select|Wrap|Line Numbers
  1. SELECT TestTable.*, PayRateCodes.Rate
  2. FROM TestTable INNER JOIN PayRateCodes
  3. ON TestTable.ID = PayRateCodes.EmployeeID AND 
  4. ON PayRateCodes.BeginDate < TestTable.Date < PayRateCodes.EndDate) OR
  5. ON TestTable.Date > PayRateCodes.BeginDate AND
  6. ON PayRateCodes.EndDate = "")];
  7.  
But where the first one just gives me the same rate for the person no matter what, this one won't rever run, because it gives me an error:

Syntax error, missing operator in expression ".


Then it highlights the following section of the SQL statement: tTable.ID =

If I attempt to logically parenthize it, it tells me my parentheses are screwed up.

-R
Jan 22 '07 #7
NeoPa
32,579 Recognized Expert Moderator MVP
Angwe,
Sorry to take so long to respond (except that it has encouraged you to get so much done by yourself which is definitely good). I'm afraid I'm still short of proper time this week (to go through everything in detail) but I hope to catch up later somewhen.
In the mean time, you don't need to repeat the ON in the FROM clause. The ANDs & ORs are sufficient on their own.
You don't want a ']' at the end.
You should parenthesise () the ANDs & ORs where necessary. It is possible to do without but harder to read and prone to error.
Lastly, if you want [StartDate] <= [YourDate] <= [EndDate] (a more usual usage) you can use the form :
Expand|Select|Wrap|Line Numbers
  1. [YourDate] Between [StartDate] And [EndDate]
A slightly fixed version :
Expand|Select|Wrap|Line Numbers
  1. SELECT TestTable.*, PayRateCodes.Rate
  2. FROM TestTable INNER JOIN PayRateCodes ON 
  3. TestTable.ID = PayRateCodes.EmployeeID AND 
  4. PayRateCodes.BeginDate < TestTable.Date < PayRateCodes.EndDate) OR
  5. TestTable.Date > PayRateCodes.BeginDate AND
  6. PayRateCodes.EndDate = "");
Jan 23 '07 #8
angwe23
9 New Member
Hey NeoPa,

Thanks for all your suggestions. Using your code I got as far as still having the same problem, but with no more syntax errors.

I finally found the way to get what I want. Blank columns of the "Date/Time" data type have to be tested with IsNull(), not the blank string ("").

After doing that, the following code does what I want!

Expand|Select|Wrap|Line Numbers
  1. SELECT TestTable.*, PayRateCodes.Rate
  2. FROM TestTable INNER JOIN PayRateCodes ON 
  3. (TestTable.ID = PayRateCodes.EmployeeID AND 
  4. ((PayRateCodes.BeginDate <= TestTable.Date <= PayRateCodes.EndDate) OR
  5. ((TestTable.Date >= PayRateCodes.BeginDate) AND
  6. (IsNull(PayRateCodes.EndDate)))));
  7.  
It may be ridiculously over-parenthized, but it works, and should be understandable. (If you take something like this into gVim, it will happily highlight the close parens that matches the open parens the cursor is over, nice, eh?)

Thanks for your help!

-R
Jan 24 '07 #9
angwe23
9 New Member
I may have been hasty. Damn.

I now get two entries for dates after the change, one for dates before the rate change.

In other words, if TestEmployee put in hours on 9/9/2005, I only get one entry at the correct rate. If TestEmployee put in hours on 2/13/2006, I get two entries, one for the first rate, and one for the second rate. Any thoughts?
Jan 24 '07 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

9
1754
by: Jordan Tiona | last post by:
I can't get this code to work right. It seems to be skipping some of the cin functions. Can someone help me with this? ClassTrack.cpp: #include <iostream> #include "ClassTrack.h" using namespace std; const MAX_CLASSES = 12;
3
1877
by: fstenoughsnoopy | last post by:
Ok the complete story. I have a Contact Table, Query and Form, that are used to input and store the contact info for customers. They have FirstName, LastName and Address as the primary key fields to keep out duplicates. I am trying to put a full name box on the query, that uses the FirstName, LastName and Middle Initial and puts them together to form a full name. That I have so far. On my order database(consisting of a master table with...
0
1854
by: harry12 | last post by:
Hello- I'm fairly new at using Microsoft Access and I'm having trouble getting a couple of things to work in my database. The first is that I have yet to find a way to get an append query to add only new records and not all the records. As an example, this query filters a list of property owners for duplicates and then appends to a table where they are assigned autonumer IDs. The problem is that I'm constantly entering new owners in and...
3
3515
by: rhobson2 | last post by:
Hello, I wrote a database applicaiton using Access XP (2002) and everything has been working good for the client until they purchased a couple of new computers with Access 2003. The meetings form has an unbound combo box listing all the meetings in the database allowing the user to navigate between meeting records. The meetings form also has a list box that displays a list of members associated with a meeting.
6
1455
by: MLH | last post by:
I have a query with a single table. One of the table fields appearing in the QBE grid is containing values from 1 to 127. Then I have the following calculated field named : Published: IIf((1 And )=1,"Sunday ","") & IIf((2 And )=2,"Monday ","") & IIf((4 And )=4,"Tuesday ","") & IIf((8 And )=8,"Wednesday ","") & IIf((16 And )=16,"Thursday ","") & IIf((32 And )=32,"Friday ","") & IIf((64 And )=64,"Saturday","")
5
1391
by: poreko | last post by:
Hi guys I am trying to compare every row of mysql database against an array. My aim is to compute the euclidean distance. This is my reference array: Array ( => 2.5 => 120 => 128 => 2 => 1000 ) And i Have written the following to compute first the difference betwenn the element.However my reference array can only be compare from the element of table i.e array. foreach($array as $i=>$value){
3
1624
by: dmorand | last post by:
I've got a table which contains some items that I need to compare against another table which contains a more detailed look at the items, and there could be multiple. Example: Table1: Field: ACETAMINOPHEN Table2: Fields: ACETAMINOPHEN ACETAMINOPHEN CHEWABLE
1
1515
by: jeddiki | last post by:
Hi, I am having difficulty seeing why my divs will not swap places :confused: I want to swap the positions of the "Hot News" and the "Todays Bonuese" sections. Here is how they look now: http://www.expert-world.com/im/images/trash1.jpg
5
13389
matheussousuke
by: matheussousuke | last post by:
Hello, I'm using tiny MCE plugin on my oscommerce and it is inserting my website URL when I use insert image function in the emails. The goal is: Make it send the email with the URL http://mghospedagem.com/images/controlpanel.jpg instead of http://mghospedagem.comhttp://mghospedagem.com/images/controlpanel.jpg As u see, there's the website URL before the image URL.
0
10647
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10386
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10398
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10133
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7669
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6889
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5554
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4339
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3017
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.