Question

I have table like this

id   action_id   inc_id   rmk   usr_id   dept_id
--   ---------   ------   ---   ------   -------
 1           1      100   NULL      15        10
 2           3      100   Test       0         0
 3           2      100   NULL       0         0
 4           4      100   NULL       0         0
 5           1      101   Text      10         8
 6           2      101   NULL       0         0

Need to select rows between action_id 1 and 4 and get previous value, I tried this

SELECT date, action_id, inc_id, lag(usr_n) OVER (ORDER BY inc_id) AS prevusr, 
lag(dept_n) OVER (ORDER BY inc_id) AS prevasvd
FROM table t1 INNER JOIN 
 usr ON t1.usr_id = usr.usr_id INNER JOIN 
 dept ON t1.svd_id = dept.dept_id

WHERE EXISTS
(
   SELECT 1 FROM table t2 
   WHERE t2.action_id='1' AND t2.inc_id=t1.inc_id
)
AND EXISTS
(
   SELECT 1 FROM table t2 
   WHERE t2.action_id='4' AND t2.inc_id=t1.inc_id
)
AND action_id IN (4, 1) 

In SQL server 2012 express it work, but not in SQL Server 2008, i have no idea how to convert it ..

Thanks

Was it helpful?

Solution

An easy way to replace lag() is with a correlated subquery. Here is an example (simplified from your query):

SELECT date, action_id, inc_id,
       (select top 1 usr_n
        from table t2
        where t2.inc_id < t.inc_id
        order by t2.inc_id desc
       ) AS prevusr,
FROM table t;

If you want to calculate the lags of multiple variables at the same time you can use apply.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top