I am getting some data (into a #temp table) that has some logical ordering.
When I'm pulling the data I'd like to add a new sequence/counter that increments only when certain conditions are met within the other fields.
Ideally something like this:
DECLARE @counter int = 0;
SELECT Item, Date, Event,
@counter = @counter +
(CASE
WHEN Event = 'Something' THEN 1
ELSE 0
END) AS EVENT_SEQ
INTO #tempTable
FROM MyData
ORDER BY Item, Date
SQL gives me two errors:
A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.
or
A SELECT INTO statement cannot contain a SELECT statement that assigns values to a variable.
The desired result
ITEM DATE EVENT EVENT_SEQ
blah 2015-01-01 nothing 1
blah 2015-01-02 nothing 1
blah 2015-01-03 nothing 1
blah 2015-01-04 something 2
blah 2015-01-05 nothing 2
blah 2015-01-06 nothing 2
blah 2015-01-07 something 3
blah 2015-01-08 nothing 3
blah 2015-01-09 nothing 3
blah 2015-01-10 nothing 3
blah 2015-01-11 nothing 3
blah 2015-01-12 something 4
blah 2015-01-13 something 5
blah 2015-01-14 nothing 5
blah 2015-01-15 nothing 5
blah 2015-01-16 nothing 5
blah 2015-01-17 nothing 5
blah 2015-01-18 nothing 5
blah 2015-01-19 nothing 5
blah 2015-01-20 something 6
blah 2015-01-21 something 7
blah 2015-01-22 nothing 7
Similar question:
SQL Server 2012: Conditionally Incrementing a counter user ROW_NUMBER()
I am using SQL 2014