473,805 Members | 2,119 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Code Listed: select max value in row that is less than my variable

daJunkCollector
76 New Member
Hey, I am having a problem with a SQL statement. I hope someone can help me.

I have a table with one key column, ID and two columns, Value and Date. I have a variable that contains a certain date. I need to select the max value whose date is less than my variable!

Expand|Select|Wrap|Line Numbers
  1. SELECT Value ,MAX(Date)
  2.     FROM myTable
  3.     WHERE ID= '565'
  4.     GROUP BY Value
  5.     HAVING MAX(Date) <= @Variable
This gives me ALL the values less than my variable, not just the max value less than my variable :(. Please help.
Apr 4 '08 #1
6 12088
ck9663
2,878 Recognized Expert Specialist
Hey, I am having a problem with a SQL statement. I hope someone can help me.

I have a table with one key column, ID and two columns, Value and Date. I have a variable that contains a certain date. I need to select the max value whose date is less than my variable!

Expand|Select|Wrap|Line Numbers
  1. SELECT Value ,MAX(Date)
  2.     FROM myTable
  3.     WHERE ID= '565'
  4.     GROUP BY Value
  5.     HAVING MAX(Date) <= @Variable
This gives me ALL the values less than my variable, not just the max value less than my variable :(. Please help.

Try using a subquery

Expand|Select|Wrap|Line Numbers
  1. select * from 
  2. (SELECT Value ,MAX(Date) as MaxDate
  3.     FROM myTable
  4.     WHERE ID= '565'
  5.     GROUP BY Value) MySubquery
  6. Where MaxDate <= @Variable

-- CK
Apr 4 '08 #2
daJunkCollector
76 New Member
CK, thank you very much for helping me. Unfortunately, I am still getting the exact same result set.

Here is the exact Query:

Expand|Select|Wrap|Line Numbers
  1. DECLARE @RequestYear  smallint
  2. DECLARE @EmployeeID   int
  3. SET @RequestYear = 2002
  4. SET @EmployeeID = 565
  5. SELECT *
  6.     FROM
  7.         (SELECT VacationHours, MAX(EffectiveDate) as MaxDate
  8.             FROM HRE_T_VAC_AvailableVacation
  9.             WHERE EmployeeID = @EmployeeID
  10.             GROUP BY VacationHours) mySubQuery
  11.     WHERE MaxDate <= CONVERT(datetime, CONVERT(varchar(4),@RequestYear))
It is still returning all rows with dates earlier than 2002 rather than just the most recent row prior to 2002.
Apr 4 '08 #3
ck9663
2,878 Recognized Expert Specialist
CK, thank you very much for helping me. Unfortunately, I am still getting the exact same result set.

Here is the exact Query:

Expand|Select|Wrap|Line Numbers
  1. DECLARE @RequestYear  smallint
  2. DECLARE @EmployeeID   int
  3. SET @RequestYear = 2002
  4. SET @EmployeeID = 565
  5. SELECT *
  6.     FROM
  7.         (SELECT VacationHours, MAX(EffectiveDate) as MaxDate
  8.             FROM HRE_T_VAC_AvailableVacation
  9.             WHERE EmployeeID = @EmployeeID
  10.             GROUP BY VacationHours) mySubQuery
  11.     WHERE MaxDate <= CONVERT(datetime, CONVERT(varchar(4),@RequestYear))
It is still returning all rows with dates earlier than 2002 rather than just the most recent row prior to 2002.
Your EffectiveDate field, I assume is a datetime column. After the subquery, executed, the Max() of EffectiveDate will be called MaxDate which is also a datetime. Your condition CONVERT(datetim e, CONVERT(varchar (4),@RequestYea r)), you are passing a year on the convert function and expecting a datetime to be returned. It will always return the first day of that year. Is that what you're trying to do?

-- CK
Apr 4 '08 #4
daJunkCollector
76 New Member
Yes that is correct.
Apr 4 '08 #5
daJunkCollector
76 New Member
Ok....if you're still with me....I made a little progress. I designed to SELECT queries. Problem is...I need to somehow combine them so that I can select both values:

Expand|Select|Wrap|Line Numbers
  1. SELECT SUM(VacationHours) AS adjustedVacation
  2.         FROM HR_VacRequest
  3.         WHERE RequestedBy = @EmployeeID AND RequestYear = @RequestYear
Expand|Select|Wrap|Line Numbers
  1. SELECT
  2.     av.VacationHours AS totalVacation
  3.         FROM HRE_T_VAC_AvailableVacation av
  4.             INNER JOIN (SELECT MAX(EffectiveDate) AS MaxEffectiveDate 
  5.                             FROM HRE_T_VAC_AvailableVacation
  6.                             WHERE EmployeeID=@EmployeeID
  7.                                 AND EffectiveDate<=CASE WHEN DATEPART(yy,GETDATE())=@RequestYear THEN GETDATE() ELSE '12/31/'+CONVERT(varchar(4),@RequestYear)+' 23:59:59' END
  8.                        ) t ON av.EffectiveDate=t.MaxEffectiveDate
  9.         WHERE EmployeeID=@EmployeeID
Apr 4 '08 #6
ck9663
2,878 Recognized Expert Specialist
Could you post some test data and what you're trying to attain?

-- CK
Apr 4 '08 #7

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

Similar topics

53
5758
by: Cardman | last post by:
Greetings, I am trying to solve a problem that has been inflicting my self created Order Forms for a long time, where the problem is that as I cannot reproduce this error myself, then it is difficult to know what is going on. One of these Order Forms you can see here... http://www.cardman.co.uk/orderform.php3
1
2088
by: SABmore | last post by:
I have the following code that populates 3 independent drop-down boxes with data from arrays. From there the user can select a value from a drop-down list, or input data into a text box. The user then submits this to be inserted into the database. Currently I've only programmed to have the first input box/drop-down valid. The problem I am having is that, even though I've inserted my SQL into a sub procedure, the code is still run prior...
2
2419
by: rked | last post by:
I get nameSPAN1 is undefined when I place cursor in comments box.. <%@ LANGUAGE="VBScript" %> <% DIM ipAddress ipAddress=Request.Servervariables("REMOTE_HOST") %> <html> <head> <meta http-equiv="Content-Type" content="text/html;
25
2358
by: Delta | last post by:
Drop Down Menu Mozilla : work well widowed elements such as drop downs, except for flash movies IE : work well so far http://pwp.netcabo.pt/falmartins/index.htm
10
2217
by: dbuchanan | last post by:
Hello, >From time to time my vb2005 form disappears and is replaced by the following errors. Rebuilding the application never helps. However the errors never affects the operation of my application that I notice, but it is very anoying. To get rid of the errors I must close the form, close the application and then reopen it.
44
2599
by: shuisheng | last post by:
Dear All, Assume there are three classes where CA has members of class CA1 and CA2 as follows. To make the public functions of CA1 and CA2 can work on the members a1 and a2 in a CA object, I just write all the functions such as a1_func1(), a1_fun2(), a2_func1(), as_func2() in the CA interface. I think this is a stupid way since if there are more functions in CA1 and CA2, I need to repeat them all. Is there any good way to implement it?
2
1129
by: Ken1 | last post by:
Hello, lets say i have a select like this: <select name="numbers" id="numbers"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> Lets say a user selects "Two" from the drop down menu... now I want to get that "Two" into a variable... but not "2" because i can get 2 by using numbers.value..... but how could i get the "Two" into a variable?
1
2677
by: dwaterpolo | last post by:
Hi Everyone, I am trying to read two text files swY40p10t3ctw45.col.txt and solution.txt and compare them, the first text file has a bunch of values listed like: y y y y y y y
14
8022
by: johndonnelly | last post by:
HI, I am trying to figure out how to write a C# program to add parameter's "A" and "B" and return "C" in the following code: I get an error at the commnd.ExecuteNonQuery(); statement below. The error states: X2 Provider Error: <ExecuteHelper Failed> X2 Provider Error: <Internal Error: Failed to get the IProc Interface> The provider works with ADO.Net according to the developer.
0
9596
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10363
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...
0
10107
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...
0
6876
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
5544
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...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4327
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
2
3846
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3008
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.