Quantcast
Channel: Forum Getting started with SQL Server
Viewing all articles
Browse latest Browse all 7129

Using With to compare previous values

$
0
0

I'm trying to write a statement that will compare the current record to the previous record and flag when there is a match on multiple conditions. I am using SQL Server Mgmnt studio to run the code.I have created a temporary DB called 'deleteme' and imported some test data.

  • I need to check if the current record has the same date as the previous
  • That the severity of the previous and current record is 4
  • That the status of the previous and current record is 40.

Can anyone tell me if I am on the right lines:

-- Define the CTE expression name and column list.
WITH data ( d_eventdate, d_severity, d_status, d_rn)
AS        (
        SELECT [Event_Date],[Severity],[MStatus],
        row_number() over (order by [Event_Date] asc) as rn
        FROM  [deleteme].[dbo].[Source$]
        )
       
     -- Define the outer query referencing the CTE name.  
 
  SELECT [Event_Date],[Severity],[MStatus], row_number() over (order by [Event_Date] asc) as c_rn
 
  FROM [deleteme].[dbo].[Source$] curr
  WHERE curr.c_rn=data.d_rn+1
  AND curr.[Event_Date]=data.d_eventdate
  AND curr.[Severity]=data.d_severity
  AND curr.[Severity]=data.d_status
  AND curr.[Severity]=10
  AND curr.[MStatus]=40;

It doesn't run and i get an error saying 'Invalid object name 'deleteme.dbo.Source$'.


Viewing all articles
Browse latest Browse all 7129

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>