Solved

Stuck on a query with row wise calculation.....

Posted on 2007-04-04
7
347 Views
Last Modified: 2012-06-27
i m trying to figure out instances from a table where two rows are inserted in less than 5 mins apart for a same customer by a different user. i have tried doing the grouping by but if the same customer was called later on during the day then it gets out of that condition....... following is the sceario that would explain it more clearly....


id        customerid          dateTime                  user
1            10                    today 9:00 am           2
2            10                    today 9:02 am           3
3            15                    today 9:05 am           6
4            15                    today 9:06 am           6
5            10                    today 9:30 am           3


In the above example the query should only bring up customer id 10.... as there was atleast one instance where there are two records less than 10 minutes apart by two different users.....  If i use group by clause and go with Max and min values comparing them to be less than 10 minutes apart for the above data set i will get empty recordset....as customerid 15 was less than 10 minutes apart but was by the same user......

i hope i explained it okay...
thanks in advance...
0
Comment
Question by:PremkumarBalwani
7 Comments
 
LVL 10

Expert Comment

by:ksaul
ID: 18851533
I think it will take an self-join like:

SELECT *
FROM YourCustomerTable c1
INNER JOIN YourCustomerTable c2 ON c1.customerid = c.customerid
WHERE ABS(DATEDIFF(minute,c1.dateTime, c2.dateTime)) > 5
AND c1.user <> c2.user
0
 
LVL 10

Expert Comment

by:RichardCorrie
ID: 18851563
i do hope u do not have a column called datetime - this is a SQL reserved word and u can get into all sorts of trouble.

try
Select
c1.id,
c1.customerid,
c1.[dateTime]
c1.user
from
Customers  c1
inner join
customers c2
on
c1.customerid = c2.customerid
and
datediff(minute,c1.[datetime],c2.[datetime]) < 5
and
c1.user <> c2.user

/Richard
0
 
LVL 14

Expert Comment

by:mherchl
ID: 18851582
try this:

select distinct a.customerid
   from yourtable a
   join yourtable b on a.customerid = b.customerid and a.user <> b.user and datediff(s, a.datetime, b.datetime) <= 60*5
0
Windows Server 2016: All you need to know

Learn about Hyper-V features that increase functionality and usability of Microsoft Windows Server 2016. Also, throughout this eBook, you’ll find some basic PowerShell examples that will help you leverage the scripts in your environments!

 
LVL 6

Expert Comment

by:DocGyver
ID: 18851642
This query could be very expensive against a table with a lot of rows.  Most likely you should add a WHERE clause to limit the scope to a given day but keep in mind if you do that you need to account for the event happening over a day boundary.  Adding something like:

WHERE DateTime > DateAdd(DD, -1, getdate())

will only look for the event in the last 24 hours

select
FROM
     MyTab T1
     JOIN MyTab T2 ON
         T1.ID <> T2.ID AND T1.CUSTOMERID = T2.CUSTOMERID AND
         ABS(T1.DateTime - T2.DateTime) < 300 AND
         T1.USER <> T2.USER
0
 
LVL 1

Author Comment

by:PremkumarBalwani
ID: 18851648
Hello,
thank you all for your solutions... is there any way i can get around without having to do a self join.... i say this because its a huge, huge table as it records history of every transaction and doing a self join would just be disastrous.....

thanks,
0
 
LVL 23

Accepted Solution

by:
Christopher Kile earned 250 total points
ID: 18852023
Frankly, this is more of an issue for a trigger.  Add a field called posted_within_5min BIT to your recordset and default it to 0.  Assume your table name is Table1:

CREATE TRIGGER ON Table1
AFTER INSERT
AS

DECLARE @id INTEGER, @customerid INTEGER
DECLARE @datetime DATETIME, @user INTEGER

DECLARE c1 READ-ONLY CURSOR FOR
SELECT
id,
customerid,
[datetime],
[user]
FROM
inserted

OPEN c1
FETCH NEXT FROM c1 INTO
      @id, @customerid, @datetime, @user
WHILE @@FETCH_STATUS = 0
BEGIN
      IF EXISTS(
            SELECT * FROM Table1
            WHERE
            customerid = @customerid
            AND
            [user] <> @user
            AND
            DATEDIFF(mi, [datetime], @datetime) < 5
            )
      BEGIN
            -- Update the master table as the
            -- insert has already taken place
            UPDATE Table1 SET
                  posted_within_5min = 1
            WHERE
                  id = @id
      END
      FETCH NEXT FROM c1 INTO
            @id, @customerid, @datetime, @user
END      


This trigger is good for one insertion or a batch insertion.  Old records can be marked using a batch update process, which will be long but will have to happen only once. Your query then becomes:

SELECT
*
FROM Table1
WHERE
posted_within_5min <> 0
0
 
LVL 1

Author Comment

by:PremkumarBalwani
ID: 18854041
thanks cpkilekofp!!

although at present i used the other solutions as a quick fix, but i will implement the trigger when i get a chance just coz its more clean and does not require huge database query everytime you run it. will just have to see how the trigger affects the performance of the data access and write in a work environment.

thank you all for your ideas...
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Load balancing is the method of dividing the total amount of work performed by one computer between two or more computers. Its aim is to get more work done in the same amount of time, ensuring that all the users get served faster.
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Via a live example, show how to backup a database, simulate a failure backup the tail of the database transaction log and perform the restore.

919 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now