Question

I would like to have a row counter in the select query of my stored procedure, but the counter would not be incremented for each row. The incrementation would depend on the value of one of the fields. Something equivalent to this invalid code:

DECLARE @RowIndex as int
SET @RowIndex = 0
SELECT
   f1, f2, f3,
   CASE
      WHEN f1 > 3 THEN @RowIndex += 1
      ELSE @RowIndex
   END AS MyIndex
FROM
   MyTable

How should I do that in SQL Server 2005?

Was it helpful?

Solution

To do this in a single query, you'll have to join the table back to itself to get the number or prior rows that meet your criteria. Also, you definitely need a column that orders the table. In this case, let's call that column f2.

SELECT a.f1, a.f2, a.f3
    , SUM(CASE WHEN b.f1 > 3 THEN 1 ELSE 0 END) AS MyIndex
FROM MyTable a
JOIN MyTable b
    ON a.f2 >= b.f2
GROUP BY a.f1, a.f2, a.f3

OTHER TIPS

SELECT f1,f2,f3, DENSE_RANK() OVER (ORDER BY tempf1)-1 AS myIndex
FROM
(
  SELECT f1, f2, f3, CASE WHEN f1>3 THEN f1 ELSE 0 END AS tempf1
  FROM
  MyTable
) AS A

Please use Dense_Rank() with order by f1 as above. Try this.

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