473,657 Members | 2,515 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Problem with query and date ranges

I'm trying to create a query that will tell me which requests
took longer than 10 days to move one from particular state to another
state. The query I've created returns the correct requests,
but not always the correct 'NextActionDate '/'NextStatus'/'NextState'.

I'm sure I'm missing something easy, but I can't figure out what it
might be. Any help is appreciated! Thanks,
Myron
-- remove SPAM-KILL from address to reply by email --
DDL for table creation and data population:

CREATE TABLE [dbo].[ReqHistory] (
[Id] [int] NOT NULL ,
[ReqId] [int] NOT NULL ,
[ReqIDStateId] [tinyint] NOT NULL ,
[ActionDate] [datetime] NOT NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[RequestStates] (
[ID] [tinyint] NOT NULL ,
[StateText] [varchar] (30) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NOT NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Requests] (
[ID] [int] NOT NULL ,
[ShortDescriptio n] [varchar] (150) COLLATE SQL_Latin1_Gene ral_CP1_CI_AS NULL ,
[StatusChangeDat e] [datetime] NULL ,
[Status] [tinyint] NULL
) ON [PRIMARY]
GO

insert into Requests values(361, 'Test ID: 361', cast('2004-06-03 08:52:03.013' as datetime),98)
insert into Requests values(1400, 'Test ID: 1400', cast('2004-05-13 04:01:55.250' as datetime),97)
insert into Requests values(30051,'T est ID: 30051', cast('2004-09-15 10:10:25.093' as datetime), 96)

insert into ReqHistory values(904,361 ,1,cast('2004-05-03 00:20:55.983' as datetime))
insert into ReqHistory values(931,361 ,2,cast('2004-05-03 01:07:14.157' as datetime))
insert into ReqHistory values(959,361 ,20,cast('2004-05-03 01:29:20.157' as datetime))
insert into ReqHistory values(20250,36 1 ,31,cast('2004-06-03 08:51:58.950' as datetime))
insert into ReqHistory values(20251,36 1 ,98,cast('2004-06-03 08:52:03.013' as datetime))
insert into ReqHistory values(20249,36 1 ,30,cast('2004-06-03 08:51:51.107' as datetime))
insert into ReqHistory values(939,361 ,10,cast('2004-05-03 01:10:36.093' as datetime))
insert into ReqHistory values(7318,140 0 ,1,cast('2004-05-13 03:48:01.420' as datetime))
insert into ReqHistory values(7346,140 0 ,2,cast('2004-05-13 03:56:37.857' as datetime))
insert into ReqHistory values(7347,140 0 ,12,cast('2004-05-13 03:57:03.293' as datetime))
insert into ReqHistory values(7356,140 0 ,22,cast('2004-05-13 04:00:58.497' as datetime))
insert into ReqHistory values(7357,140 0 ,97,cast('2004-05-13 04:01:55.250' as datetime))
insert into ReqHistory values(53218,30 051,1,cast('200 4-08-06 10:12:33.050' as datetime))
insert into ReqHistory values(53223,30 051,2,cast('200 4-08-06 10:15:32.500' as datetime))
insert into ReqHistory values(53246,30 051,13,cast('20 04-08-06 10:26:34.850' as datetime))
insert into ReqHistory values(53264,30 051,23,cast('20 04-08-06 10:47:38.993' as datetime))
insert into ReqHistory values(70138,30 051,3,cast('200 4-09-15 09:21:18.230' as datetime))
insert into ReqHistory values(70257,30 051,96,cast('20 04-09-15 10:10:25.093' as datetime))

insert into RequestStates values(1,'Await ing CSMC')
insert into RequestStates values(2,'CSMC Review')
insert into RequestStates values(3,'Rejec t Awaiting CSMC')
insert into RequestStates values(10,'Awai ting MA Review')
insert into RequestStates values(12,'Awai ting FO Review')
insert into RequestStates values(13,'Awai ting IS Review')
insert into RequestStates values(20,'MA Review')
insert into RequestStates values(22,'FO Review')
insert into RequestStates values(23,'IS Review')
insert into RequestStates values(30,'Func Approval')
insert into RequestStates values(31,'Func Approval Complete')
insert into RequestStates values(96,'Reso lved')
insert into RequestStates values(97,'Plan ning')
insert into RequestStates values(98,'Open ')
insert into RequestStates values(99,'Clos ed')
The query that almost works:

select irh.ReqID, irh.MAactiondat e, irh.reviewstate ,
irh2.Nextaction date, irh2.irh2state as NextStatus, irh2.statetext as NextState
from (select distinct irh.ReqID, max(irh.actiond ate) as MAactiondate,
irh.ReqIDStateI D As IRHState, irs.statetext as ReviewState
from ReqHistory IRH
join requeststates irs on irs.id = irh.ReqIDStateI D
where irh.ReqIDStateI D in (20, 23)
group by irh.ReqID, irs.statetext, irh.ReqIDStateI D) as irh
join (select irh2.actiondate as NextActiondate, irh2.ReqID, irh2.IRH2State, irs.statetext
from (select min(actiondate) as actiondate, ReqID,
min(ReqIDStateI D) as IRH2State
from ReqHistory
--the WHERE is wrong, and I believe should be irh2.Nextaction date > irh.maactiondat e,
--but I couldn't make it work
where ReqIDStateID > 23
group by ReqID) as irh2
join RequestStates irs on irs.id = irh2.irh2state ) as irh2 on irh.ReqID = irh2.ReqID
join requests ir on ir.id = irh.ReqID
where irh.MAactiondat e + 10 < irh2.Nextaction date
order by irh.ReqID
The data being returned is:
(the 'time' portion of the dates edited out for space)

ReqID MAActionDate Review State NextActiondate NextStatus NextState
361 2004-05-03 MA Review 2004-06-03 30 Functional Approval
30051 2004-08-06 IS Review 2004-09-15 96 Resolved

The data that should have been returned:
(the 'time' portion of the dates edited out for space)

ReqID MAActionDate Review State NextActiondate NextStatus NextState
361 2004-05-03 MA Review 2004-06-03 30 Functional Approval
30051 2004-08-06 IS Review 2004-09-15 3 Reject Awaiting CSMC
Jul 23 '05 #1
3 1733
Holy subqueries batman!

Thanks for including the DDL... it made finding an answer to this much
easier. A couple quick notes though... you didn't include and foreign
or primary keys. That combined with the inconsistent naming standards
made it a little difficult to understand the code.

The following code returned what you were expecting. The code assumes
that no two actions can occur at the same exact time. If that
assumption is incorrect then the code will not work correctly in those
situations.

Also, instead of the NOT EXISTS you could of course opt to use a LEFT
OUTER JOIN along with checking for IS NULL on one of the PK columns for
the table (RH). That often gives better performance than NOT EXISTS in
my experience.

HTH,
-Tom.

SELECT MAH.ReqID, MAH.ActionDate, RS.StateText, NA.ActionDate,
NA.ReqIDStateID , NS.StateText
FROM ReqHistory MAH
INNER JOIN ReqHistory NA ON NA.ReqID = MAH.ReqID
AND NA.ActionDate > DATEADD(dy, 10,
MAH.ActionDate)
INNER JOIN RequestStates RS ON RS.ID = MAH.ReqIDStateI D
INNER JOIN RequestStates NS ON NS.ID = NA.ReqIDStateID
WHERE MAH.ReqIDStateI D IN (20, 23)
AND NOT EXISTS (SELECT *
FROM ReqHistory RH
WHERE RH.ReqID = MAH.ReqID
AND RH.ActionDate > MAH.ActionDate
AND RH.ActionDate < NA.ActionDate)

Jul 23 '05 #2
"Thomas R. Hummel" <to********@hot mail.com> wrote:
Holy subqueries batman!

Thanks for including the DDL... it made finding an answer to this much
easier. A couple quick notes though... you didn't include and foreign
or primary keys. That combined with the inconsistent naming standards
made it a little difficult to understand the code.

<some snippage>

Thanks for the speedy and accurate answer, Tom! Your query looks a
lot more elegant than my monster, and it found rows that my original
was dropping. :)
Myron

Jul 23 '05 #3
Your basic design is wrong. Time comes in durations and not points --
look at everyone from Zeno to the ISO standards. Also, your data
element names make no sense -- "ReqIDStateId"? ?? if something is a
state, then it is a value and not an indentifier. What is the vague
"ID": floating around? Surely you do not blindly use sequentail
numbering in an RDBMS to mimic a sequential file physical record
number!

CREATE TABLE RequestHistory
( request_nbr INTEGER NOT NULL ,
request_status INTEGER NOT NULL
REFERENCES RequestStatusCo des(request_sta tus)
ON UPDATE CASCADE,
start_date DATETIME DEFAULT CURRENT TIMESTAMP NOT NULL,
end_date DATETIME, -- null means current
PRIMARY KEY (request_nbr, start_date ));
I'm trying to create a query that will tell me which requests took

longer than 10 days to move one from particular state to another state.
<<

Trival with the right design, isn't it?

Jul 23 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
1467
by: Gregory Konev | last post by:
Hello, All! Example. I have a table with information about payments (id, amount, pay_date, customer_id). Can I select two sums for two different date ranges, grouped by 'customer_id' (for each customer) in one query? -- With best regards, Gregory Konev. E-mail: voyage@ml.net.ua
7
4042
by: Thomas R. Hummel | last post by:
Hello all, I am trying to write a query that compares a member's enrollment period with the products that their group has had during that period (all members belong to a group and the products that the member has are based on that group). I need to get the date range for all products that the member had during their enrollment. Here are a few rules: - In the source table there are some group products that have two
17
25894
by: Lapchien | last post by:
My table has a record called date/time - filled (not surprisingly) with a date and time. I can format the date in one query field, also the time, using format in an expression. My user wants me to provide a listing of all table entries between 22:00 and 07:30 the next day, between a given set of dates (typically one week apart but in practice between any dates specified). My query works ok for 1 date - entering 2 dates, one for 22:00 -...
1
2232
by: Dalan | last post by:
I have attempted to resolve a problem regarding erroneous output using a Between And parameter on several Access 97 queries, but to no avail. The queries are used for report output and regardless of the beginning and ending dates entered, the reports show all activity including before and after the dates entered. There is a frmAccount and two subforms sfrmPurchase and sfrm Sales. In order to isolate costs for each collectively, both...
4
7002
by: Dave Boyd | last post by:
Hi, I have two very similar forms each with a subform. The main form gets a few fields from the user and passes this back to a query that the subform is bound to. The requery is done when the user enters the last qualifying field on the main form. In one case this works fine, the subform shows the data the user wants to update -- which means showing all the data put in previously (ie showing this via the requery and the continuous...
0
1094
by: Jim in Arizona | last post by:
I built a ticket system a while back but I never could get the queries quite right. My queries work as long as I don't use a date range. Here is the code I use for the query portion (the relevant part): If ddlReportType.SelectedValue = "Everything" And ddlQueryTechnician.SelectedValue = "Select All" Then strSQLCount = "SELECT COUNT(*) FROM TTickets WHERE dtemp BETWEEN CONVERT(DATETIME, " & _ "'" & bd & "', 110) AND CONVERT(DATETIME, '"...
14
4431
by: peteh | last post by:
Hi All; We have many production jobs that "load from cursor" to a UDB/AIX 8.2 (with dpf) data warehouse from source tables residing Oracle 9i. Since Oracle dates are (roughly) equivalent to DB2 timestamps, we frequently use the date() function to "convert" from the Oracle date datatype to the DB2 date datatype. We have used this technique on over 20 Oracle tables for several months with no problem. One table in particular fails with a...
9
6018
by: mharrison | last post by:
Hello, I am developing a small java web-based car-pool booking system app which interacts with an access database. I am trying to write 2 queries: The first which will specify whether a given car is available on a given date range e.g. from: 1/12/05 to 12/12/05. the second which will run if the first query is unsuccessful e.g. a list of other cars available on the chosen dates. I have been looking at a Microsoft page which I believe may help...
22
5007
by: boliches | last post by:
I am trying to get a crosstab query (in access 2000) to group data by date range. TRANSFORM Sum(tblInvoice.InvBalance) AS SumOfInvBalance SELECT tblInvoice.DealerID, Sum(tblInvoice.InvBalance) AS FROM tblInvoice GROUP BY tblInvoice.DealerID PIVOT Format(Now(),"ww"); I know the above code is wrong! My question is how do I get the query to group outstanding Invoice Balances (InvBalance) into the following date ranges (InvDate): 0 - 29...
1
2183
by: cryptotech2000 | last post by:
I am trying to filter this query based on date ranges but it don't seem to be working correctly, its probably something really simple if anyone can help me with this select ReceivedDate,orderstatus WHERE RecieveDate BETWEEN ''20071101' AND '20071231' ,count(case when dcoc = '88' then 1 end) as cnt88 ,sum(case when dcoc = '88' then ordertotal end) as sls88 from orders group by ReceivedDate,orderstatus order by...
0
8421
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8325
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
8844
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
8742
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
8518
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
5643
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
4173
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
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1971
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.