Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Logical problem in sql query

Author  Topic 

Hari k
Starting Member

5 Posts

Posted - 2013-11-14 : 05:34:37
Hi I am new to mysql database So can one help to my problem to resolve. I hava table "eventdata" like below
deviceID accountID timestamp speedKPH address
--------- -------- ---------- ---------- ----------------- -------------
preva1 bolero 1359088786 8.4729 Ullalu Road

preva1 bolero 1359088796 0 Ullalu Road

preva2 bolero 1359088886 0 nice Road

preva3 bolero 1359088886 8.47 Ullalu Road

preva1 bolero 1359088986 0 nice Road

preva3 bolero 1359088986 8.4729 Ullalu Road

preva1 bolero 1359088996 31 Baneerugatta

preva1 bolero 1359088998 0 Kail roald
preva3 bolero 1359088786 32
preva1 bolero 1359088896 34 Bhel

preva2 bolero 1359088786 24 Ullalu Road

preva1 bolero 1359088766 0 nice Road
preva1 bolero 1359088789 0 Nayagara

Here i need output table will be like shown below
accountID deviceID timestamp1 timestamp2 Diffstp


preva1 bolero 1359088766 1359088789 23


preva1 bolero 1359088789 1359088796 7

preva1 bolero 1359088796 1359088987 191


preva1 bolero 1359088987 1359088998 11

preva1 bolero 1359088998

can any one help for me to do this

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-11-14 : 05:41:14
do you mean this?


;With CTE
AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY deviceID, accountID ORDER BY [timestamp]) AS Rn,deviceID, accountID, [timestamp]
FROM Table
)
SELECT c1.*,c2.[timestamp],c2.[timestamp] - c1.[timestamp] AS Diffstp
FROM CTE c1
LEFT JOIN CTE c2
ON c1.deviceID = c2.deviceID
AND c1.accountID = c2.accountID
AND c1.Rn = c2.Rn - 1


EDIT: Just noticed you're using mysql
what i've given is a t-sql query as its ms sql server forum so not sure whether it will work in MySQL. In that case try your luck at some mysql forums like www.dbforums.com
------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page

bitsmed
Aged Yak Warrior

545 Posts

Posted - 2013-11-14 : 13:14:22
Generic sql might work:

select a.accountid
,a.deviceid
,a.timestamp as timestamp1
,min(b.timestamp) as timestamp2
,min(b.timestamp)-a.timestamp as diffstp
from eventdata as a
left outer join eventdata as b
on b.accountid=a.accountid
and b.deviceid=a.deviceid
and b.timestamp>a.timestamp
group by a.accountid
,a.deviceid
,a.timestamp

btw. your output doesn't match your provided sample data (I don't see timestamp 1359088987 anywhere)
Go to Top of Page
   

- Advertisement -