SQL Server 2005 - Counter in a select query
-
14-11-2019 - |
题
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?
解决方案
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
其他提示
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.
不隶属于 StackOverflow