473,651 Members | 3,007 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

sql sub query question with count

Hi,

Situation:
Need a query to return number of ticket records by month of open in a
log table where the ticket open record is older than 24 hours then the
ticket pending or ticket closed record. Tickets can also only have a
closed record with no open record.

Sample data table:
ticket_id date_log status_name status_id
13 8/21/2002 10:11:23 AM Open 1
13 8/21/2002 10:12:06 AM Closed 3
14 8/21/2002 10:16:54 AM Closed 3
14 8/21/2002 10:16:35 AM Open 1
15 8/21/2002 10:22:19 AM Open 1
15 8/21/2002 12:30:15 PM Open 1
15 8/21/2002 2:06:09 PM Open 1
15 8/23/2002 9:34:39 AM Open 1
15 8/23/2002 9:57:38 AM Open 1
15 8/23/2002 10:02:39 AM Closed 3
92 8/22/2002 4:38:24 PM Open 1
92 8/22/2002 4:45:59 PM Closed 3
93 8/23/2002 8:55:41 AM Open 1
93 8/23/2002 9:06:27 AM Closed 3
94 8/23/2002 8:59:17 AM Open 1
94 8/26/2002 9:22:27 AM Closed 3
98 8/23/2002 9:45:48 AM Open 1
98 8/26/2002 9:20:17 AM Closed 3
980 10/1/2002 9:55:25 AM Open 1
980 10/1/2002 9:55:36 AM Closed 3
1183 10/11/2002 9:58:25 AM Closed 3
1184 10/11/2002 10:03:17 AM Closed 3
1185 10/11/2002 10:05:51 AM Closed 3
1225 10/14/2002 10:56:47 AM Open 1
1225 10/16/2002 1:40:06 PM Pending 2
1225 10/17/2002 11:21:48 AM Pending 2
1225 10/17/2002 1:51:30 PM Pending 2
1225 10/18/2002 9:59:49 AM Pending 2
1225 10/18/2002 2:50:39 PM Closed 3
1225 5/11/2003 12:05:29 PM Closed 3

Current query:
SELECT DISTINCT DATEPART(mm, date_clean) AS month_name,
(SELECT count(DISTINCT t_id)
FROM log_tickets t1
WHERE (t_id = t2.t_id) AND (DATEDIFF(hh,
(SELECT TOP 1 date_log
FROM log_tickets t1
WHERE (t_id = t2.t_id) AND (status_id = 1)
)
,
(SELECT TOP 1 date_log
FROM log_tickets t1
WHERE (t_id = t2.t_id) AND (status_id = 2 OR status_id
= 3)
)
)
)>24) AS late_tickets
FROM dbo.log_tickets t2

Current Output:
month_name late_tickets
10 1
8 0
8 1
10 0

This is the output of what I would like:
month_name late_tickets
8 3
10 2

Any help would be appreciated.
Thanks,
Sam
Jul 20 '05 #1
4 22698
[posted and mailed, please reply in news]

Spark (sp***@adsgroup .net) writes:
Need a query to return number of ticket records by month of open in a
log table where the ticket open record is older than 24 hours then the
ticket pending or ticket closed record. Tickets can also only have a
closed record with no open record.


First a general piece of advice. When posting a query like this,
it is adviceable to include CREATE TABLE statements for the involved
tables and INSERT statements for the sample data. Had you done this
I would have been able to suggest a tested solution.

What follows here is completely untested:
SELECT Month(coalesce( cl.last_closed, op.first_open)) , COUNT(*)
FROM (SELECT ticked_id, first_open = MIN(date_log)
FROM log_tickets
WHERE status_id IN (1, 2)
GROUP BY ticked_id) AS op
FULL JOIN
(SELECT ticked_id, last_closed = MAX(date_log)
FROM log_tickets
WHERE status_id = 3
GROUP BY ticket_id) AS cl ON op.ticket_id = cl.ticket_id
WHERE datediff(ss, coalesce(op.fir st_open, '19000101'),
coalesce(cl.las t_closed, '99991231') > 86400
GROUP BY Month(coalesce( cl.last_closed, op.first_open))

I like to note that there are a couple of things that were
unspecified in your post:

o If a ticket has more than one Open/Pending entry, which counts,
first or last? (I have assumed first.)
o Likewise, what if a ticket is closed more than once.
o If a ticket is opened one month, and closed another for which
month should it be included? (I have assumed month it was closed.)
o You don't mention the possibility that a ticket is not closed. The
query above will include such tickets in the listing.
--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #2
>Re: sql sub query question with count
From: Erland Sommarskog
Date Posted: 8/15/2003 3:23:00 PM What follows here is completely untested:
SELECT Month(coalesce( cl.last_closed, op.first_open)) , COUNT(*)
FROM (SELECT ticked_id, first_open = MIN(date_log)
FROM log_tickets
WHERE status_id IN (1, 2)
GROUP BY ticked_id) AS op
FULL JOIN
(SELECT ticked_id, last_closed = MAX(date_log)
FROM log_tickets
WHERE status_id = 3
GROUP BY ticket_id) AS cl ON op.ticket_id = cl.ticket_id
WHERE datediff(ss, coalesce(op.fir st_open, '19000101'),
coalesce(cl.las t_closed, '99991231') > 86400
GROUP BY Month(coalesce( cl.last_closed, op.first_open))
I added an extra closed paranthesis to this line:
"coalesce(cl.la st_closed, '99991231')) > 86400"

I get this error:
Server: Msg 535, Level 16, State 1, Line 1
Difference of two datetime columns caused overflow at runtime.
As per suggestion, I have included more information.
o If a ticket has more than one Open/Pending entry, which counts,
first or last? (I have assumed first.)
Actually in this case, Pending and Closed mean the same thing. If
there is more than one Pending/Closed entry, the first one counts.
o Likewise, what if a ticket is closed more than once.
Use the first closed entry.
o If a ticket is opened one month, and closed another for which
month should it be included? (I have assumed month it was closed.)
Yep.
o You don't mention the possibility that a ticket is not closed. The
query above will include such tickets in the listing.


Forgot about this case. Thanks for including it.

CREATE TABLE [dbo].[log_tickets] (
[ticket_id] [int] NOT NULL ,
[date_log] [datetime] NOT NULL ,
[status_name] [nvarchar] (50) NULL ,
[status_id] [smallint] NULL
) ON [PRIMARY]
GO

INSERT INTO log_tickets VALUES (13,'8/21/2002 10:11:23 AM','Open',1)
INSERT INTO log_tickets VALUES (13,'8/21/2002 10:12:06 AM','Closed',3)
INSERT INTO log_tickets VALUES (14,'8/21/2002 10:16:54 AM','Closed',3)
INSERT INTO log_tickets VALUES (14,'8/21/2002 10:16:35 AM','Open',1)
INSERT INTO log_tickets VALUES (15,'8/21/2002 10:22:19 AM','Open',1)
INSERT INTO log_tickets VALUES (15,'8/21/2002 12:30:15 PM','Open',1)
INSERT INTO log_tickets VALUES (15,'8/21/2002 2:06:09 PM','Open',1)
INSERT INTO log_tickets VALUES (15,'8/23/2002 9:34:39 AM','Open',1)
INSERT INTO log_tickets VALUES (15,'8/23/2002 9:57:38 AM','Open',1)
INSERT INTO log_tickets VALUES (15,'8/23/2002 10:02:39 AM','Closed',3)
INSERT INTO log_tickets VALUES (92,'8/22/2002 4:38:24 PM','Open',1)
INSERT INTO log_tickets VALUES (92,'8/22/2002 4:45:59 PM','Closed',3)
INSERT INTO log_tickets VALUES (93,'8/23/2002 8:55:41 AM','Open',1)
INSERT INTO log_tickets VALUES (93,'8/23/2002 9:06:27 AM','Closed',3)
INSERT INTO log_tickets VALUES (94,'8/23/2002 8:59:17 AM','Open',1)
INSERT INTO log_tickets VALUES (94,'8/26/2002 9:22:27 AM','Closed',3)
INSERT INTO log_tickets VALUES (98,'8/23/2002 9:45:48 AM','Open',1)
INSERT INTO log_tickets VALUES (98,'8/26/2002 9:20:17 AM','Closed',3)
INSERT INTO log_tickets VALUES (980,'8/28/2002 9:30:25 AM','Open',1)
INSERT INTO log_tickets VALUES (980,'9/1/2002 9:40:36 AM','Closed',3)
INSERT INTO log_tickets VALUES (980,'9/1/2002 9:55:25 AM','Open',1)
INSERT INTO log_tickets VALUES (980,'9/1/2002 9:55:36 AM','Closed',3)
INSERT INTO log_tickets VALUES (1183,'9/11/2002 9:58:25
AM','Closed',3)
INSERT INTO log_tickets VALUES (1184,'9/11/2002 10:03:17
AM','Closed',3)
INSERT INTO log_tickets VALUES (1185,'9/11/2002 10:05:51
AM','Closed',3)
INSERT INTO log_tickets VALUES (1225,'9/14/2002 10:56:47 AM','Open',1)
INSERT INTO log_tickets VALUES (1225,'9/16/2002 1:40:06
PM','Pending',2 )
INSERT INTO log_tickets VALUES (1225,'9/17/2002 11:21:48
AM','Pending',2 )
INSERT INTO log_tickets VALUES (1225,'9/17/2002 1:51:30
PM','Pending',2 )
INSERT INTO log_tickets VALUES (1225,'9/18/2002 9:59:49
AM','Pending',2 )
INSERT INTO log_tickets VALUES (1225,'9/18/2002 2:50:39
PM','Closed',3)
INSERT INTO log_tickets VALUES (1225,'5/11/2003 12:05:29
PM','Closed',3)
Thanks for your help.
We are getting closer.
Sam
Jul 20 '05 #3
Please post DDL, so that people do not have to guess what the keys,
constraints, Declarative Referential Integrity, datatypes, etc. in
your schema are. You ask people to help you for free, but you don't
give us any specifications we can use, no sample data, and no DDL.

Your design is wrong. The ticket is an entity and to exist an entity
must have a duration (Einstein). This is one of many reasons I keep
telling people that a row is not a record, as you seem to think. A
row is a complete fact in itself; a record does not have to be. You
modeled the PHYSICAL, written lines from a paper form, not the LOGICAL
fact that you need. Hence, you get a crappy, complex query that runs
like glue.

CREATE TABLE Tickets
(ticket_nbr INTEGER NOT NULL PRIMARY KEY
start_time DATETIME NOT NULL,
finish_time DATE, -- null means still open
status_code INTEGER NOT NULL
CHECK (status_code IN (1, 2, 3)),
CHECK (start_time < finish_time),
-- I am guessing at this business rule
CHECK (CASE WHEN status_code = 1 AND finish_time IS NULL
THEN 1
WHEN status_code IN (2,3) AND finish_time IS NOT NULL
THEN 1 ELSE 0 END = 1)
);
Need a query to return number of ticket records by month of open in a log table where the ticket open record [sic] is older than 24 hours
than the ticket pending or ticket closed record [sic]. <<

Now the anser is easy; remember to COALESCE(finish _time,
CURRENT_TIMESTA MP) in the query to handle things that are still open.
Tickets can also only have a closed record [sic] with no open

record [sic]<<

Please write the constraint that enforces that business rule. I think
that you meant that a ticket must be open before it can be closed or
pending. Also use ISO-8601 time formats for portability.
Jul 20 '05 #4
Spark (sp***@adsgroup .net) writes:
I get this error:
Server: Msg 535, Level 16, State 1, Line 1
Difference of two datetime columns caused overflow at runtime.


Oops! This was due the combination the values to cover tickets still
open, or tickets that only were closed, and my zeal to get an accurate
expression of 24 hours. datediff() works by counting boundaries, thus:

select datediff(hh, '20021212 00:56:00', '20021213 00:09:22')

yields 24.

The remaining issue should be easy to sort out on your own, just change
MAX to MIN, and move the two around. But since you included CREATE TABLE
and INSERT statemetns, I was able to test this modified query:

SELECT Month(coalesce( cl.first_closed , op.first_open)) , COUNT(*)
FROM (SELECT ticket_id, first_open = MIN(date_log)
FROM log_tickets
WHERE status_id = 1
GROUP BY ticket_id) AS op
FULL JOIN
(SELECT ticket_id, first_closed = MIN(date_log)
FROM log_tickets
WHERE status_id IN (2, 3)
GROUP BY ticket_id) AS cl ON op.ticket_id = cl.ticket_id
WHERE datediff(ss, coalesce(op.fir st_open,
dateadd(day, -2, cl.first_closed )),
coalesce(cl.fir st_closed,
dateadd(day, 2, cl.first_closed ))) > 86400
GROUP BY Month(coalesce( cl.first_closed , op.first_open))

I got the results:

Month Count
----------- -----------
8 3
9 5

This appears to match the test data.
--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #5

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

Similar topics

0
1687
by: Sridharan | last post by:
Hello All, Below is how my data looks like Branch Item Customer Sales 10 1 C1 300 10 1 C2 400 10 1 C3 200 10 2 C1 500
0
888
by: Maury | last post by:
Hy, I have a problem showing results from a query with parameters (in Access) into a datagrid, if I use this code I receive a System.NullReferenceException DataTable myDt = new DataTable(); OleDbConnection myConnection = new OleDbConnection(ConfigurationSettings.AppSettings); OleDbCommand myCommand = new OleDbCommand(); myCommand.Parameters.Add("Data", DayToShow); //DayToShow is a variable of type DateTime myCommand.Connection =...
1
1967
by: Michal Hlavac | last post by:
hello, I have table with text attribute and fulltext index... is it possible to do query with result: word or phrase, count for example: SELECT word, my_count(word) FROM table WHERE expression.
3
6325
by: Rodríguez Rodríguez, Pere | last post by:
Hello, I think I have found a query problem when the query has an alias for a table and use alias item and table name. I ilustrate the problem with a simple table and query. prr=# create table foo (c1 int2, c2 int2); CREATE TABLE prr=# insert into foo values (1, 1);
1
3507
newnewbie
by: newnewbie | last post by:
Desperately need help in creating a query to count unique values in a table. I am a Business analyst with limited knowledge of Access….My boss got me ODBC connection to the underlying tables for our system and thinks I am omnipotent now and can extract any data out of it in the form he wants….The truth is, though I know SOME Access, I am not a programmer…and many queries that he wants me to do have a potential of being monstrous towers of...
1
2531
by: veaux | last post by:
Might not have explained this correctly in subject, but query results look like below: Name ID Phone Bill 001 123 Bill 001 234 Bill 001 456 Sam 002 999 Mary 003 888
2
4423
by: dvelst | last post by:
Hi All, I have the following query which was based on a working query in MySQL: (don't be afraid of the size of the query you see below, later on I will concentrate on part of this query) SELECT count(*) FROM ((SELECT * FROM tileinfo where julianDay BETWEEN DATE2JDAY(('2003-03-01 00:00:00'),0) AND DATE2JDAY(('2003-03-01 23:59:59' ),0) AND intersects(tile, geomFromText('POLYGON((-10.84 35.8,18.14 35.8,18.14 59.41,-10.84 59.41,-10.84...
3
2505
by: Hasse1982 | last post by:
Hi I have a table KDOCUMENT with the columns , , , , , ,
1
2205
by: Noorain | last post by:
sir i want a query which count total student. here 6 record of student. here one student two times entry. my result is total student 5. i can't do this. my table is: id stu_name dob 1 Saima 2009-02-01 2 Tanvir 2009-02-11 3 Saima 2009-02-01 4 Rumman 2009-02-01
0
8361
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
8278
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
8807
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
8701
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
8584
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
7299
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4290
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2701
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
1
1912
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.